Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementation CyberSource in Python
I am trying to implement CyberSource´s Microform in Python, but there is a problem with the captureContext I am sending to the frontend. This is the message error: r {name: 'MicroformError', reason: 'CAPTURE_CONTEXT_INVALID', message: 'You have not supplied a valid capture context.', informationLink: 'https://www.cybersource.com/products/payment_security/secure_acceptance', correlationId: undefined, …} correlationId: undefined details: undefined informationLink: "https://www.cybersource.com/products/payment_security/secure_acceptance" message: "You have not supplied a valid capture context." name: "MicroformError" reason: "CAPTURE_CONTEXT_INVALID" captureContext I am sending is something like this: {"kty":"RSA", "use":"enc", "kid":"08ajMBidgTrHvGJVzpR3ZxrNylkXqVA1", "n":"i6vpy5CdziPfwAMk6YyQxfLE2xGjA11gRzp1pL_LwIL87gSSsevZgRRVkI_Y2Jv95wT12O0DgumypVeHcGXmW5oR5tBJNhGp61f2qYHhl4PGMXyYFZ5OTgRYfJ2le0OYL4F4eQdqGd25ghq3qJkMvEN-USLyEGsNfeLwGvHsVtlJK9_QnKshcc-2oT2sKSNIkwxs7FH6afHc67WJUCFtqQQARJBX45O47MSlRbpRHAqJkw2zD35l6RDMQpRAKLzbJ9-cmsZpdWAhCTAvaSU2yH-LvVeEvzfDjWPrd6QcPpV_FYHxO1lHE18rmJHFTow6-LURaLQwl1PuG-C7PI2pZw", "e":"AQAB"} I am using this code to generate the key: def generate_key(compra, medio_pago): encryptionType = "RsaOaep" targetOrigin = "http://localhost:8000" requestObj = GeneratePublicKeyRequest( encryption_type = encryptionType, target_origin = targetOrigin ) requestObj = del_none(requestObj.__dict__) requestObj = json.dumps(requestObj) format = "legacy" try: config_obj = PagoCyberSource(medio_pago).get_configuration() api_instance = KeyGenerationApi(config_obj) return_data, status, body = api_instance.generate_public_key(format, requestObj) print("\nAPI RESPONSE CODE : ", status) print("\nAPI RESPONSE BODY : ", body) return return_data except Exception as e: print("\nException when calling KeyGenerationApi->generate_public_key: %s\n" % e) And these are the Microform and scripts ({{boton_compra.jwk}} is the captureContext): <h1>Checkout</h1> <div id="errors-output" role="alert"></div> <form action="/token" id="my-sample-form" method="post"> {% csrf_token %} <div class="form-group"> <label for="cardholderName">Name</label> <input id="cardholderName" class="form-control" name="cardholderName" placeholder="Name on the card"> <label id="cardNumber-label">Card Number</label> <div id="number-container" class="form-control"></div> <label for="securityCode-container">Security Code</label> <div id="securityCode-container" class="form-control"></div> … -
Django regroup tag get fields values
I have a web page where I have 2 models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the model Products since is the one the page is using to show the products. When I try to filter catching the value from the regroup and pass it to my view: class Categoria_Filter(ListView): model = Productos paginate_by = 10 template_name = 'mail/category-filter.html' def get_queryset(self): categoria = self.kwargs['slug'] print(categoria) if categoria == 'Todos': return Productos.objects.all() else: return Productos.objects.filter(categoria = categoria) I get the following result when printing: GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>]) which according to the docs is a namedtuple() I have tried the following: print(getattr(categoria, 'GroupedResult')) print(getattr(categoria, 'grouper')) print(getattr(categoria, 'Categorias')) They all give me: AttributeError: 'str' object has no attribute 'whatever field I have tried* Also, I print by index and for example: print(categoria[1]) gives me r Which I know is the r from GroupedResult and what I want to get from the namedtuple is Guantes de Box not: GroupedResult(grouper=<Categorias: **Guantes de Box**>, list=[<Productos: Guantes … -
The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead
So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched many times but without luck. If someone can help me I would be grateful. So that is my the error:enter image description here Then there is my views: enter image description here The html, and jquery/css: enter image description here and finaly my add func: enter image description here I have to return the quantity with the success console log in the ajax in the chrome console. I tried to change the data type, adding more advanced error func to show me more indept error in the browser, refreshing the session, watched all the names that I have to see if I typed some name wrong. -
'User' object has no attribute 'user', Where is the problem?
My goal is to reset the password via mail. But the profile_obj of the ChangePassword view returns None and 'NoneType' object has no attribute 'user'. Why? I tried different ways but did not work. The ForgetPassword view working well. The ChangePassword view doesn't work. Where is the problem? views.py: def ForgetPassword(request): try: if request.method == 'POST': email = request.POST.get('email') if not User.objects.filter(email=email).first(): messages.warning(request, 'Not email found with this email.') return redirect('ForgetPassword') user_obj = User.objects.get(email = email) token = str(uuid.uuid4()) send_forget_password_mail(user_obj.email , token) messages.success(request, 'Please check your mail box an email is send.') return redirect('ForgetPassword') except Exception as e: print(e) context = { } return render(request, "forget_password_email.html", context) def ChangePassword(request, token): context = {} try: profile_obj = User.objects.filter(forget_password_token=token).first() print(profile_obj) if request.method == 'POST': new_password = request.POST.get('new_password') confirm_password = request.POST.get('reconfirm_password') user_id = request.POST.get('user_id') if user_id is None: messages.warning(request, 'No user id found.') return redirect(f'/ChangePassword/{token}/') if new_password != confirm_password: messages.warning(request, 'both should be equal.') return redirect(f'/ChangePassword/{token}/') profile_obj.password = new_password profile_obj.save() user_obj = User.objects.get(id = user_id) user_obj.set_password(new_password) user_obj.save() return redirect('Login') context = {'user_id' : profile_obj.user.id} except Exception as e: print(e) context = { } return render(request,'change_password.html', context) helpers.py: from django.core.mail import send_mail from django.conf import settings def send_forget_password_mail(email , token ): subject = 'Your … -
custom error handler django when using django-hosts
I have a system that has deployed django-hosts, all is working fine. Until now I have been handling 404 and 500 errors for production by utilizing the neat trick of just placing files 500.html and 404.html in the root of the templates folder. This very nicely handles these errors in production (debug=False). However, now I want to get a little more creative with my error handling messaging and feedback to the user. I have other projects where I have created a custom view for the error handling. e.g. def custom_error_500(request, exception=None): print ('error 500 ') #For debugging to verify view is being processed. return render(request, "errors/500.html", status=500) and then set this parameter at the bottom of the urls.py (appname is 'main') handler500 = 'main.errorviews.custom_error_500' This all works very nicely in a project that does NOT use django-hosts. The advantage of creating the custom view is that the context is past to the RequestContext to the template, whereas by default not the case (see reference). Now, I know with django-hosts here is magic going on in the way urls.py are processed for each host. Could this be the reason why?. I tried placing the hander500 setting in all the possible urls.py … -
Can't not load static or media file, only load static when i put files in staticfiles then colllectstatic Django
I tried to put files to static, but even when i have file in static, i still can't open them in localhost.I can't use them until i put them in staticfiles and then python manage.py collectstatic. Here is my setting: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join (BASE_DIR, "staticfiles"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') My models class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # owner = models.ForeignKey( # User, # on_delete=models.CASCADE, # related_name='topic_content_type' # ) name = models.CharField(max_length=200) avatar = models.ImageField(default='default.jpg', upload_to='static/images') def __str__(self): return self.user.username i try to put file in media either, but even when i have media in my folder and have the right path, it still doesn't work. i run local host with postgres db. How can i use static file in my folder, don't need to use collectstatic everytime i put more file in static. -
How does Python "mysqlclient/MySQLdb" know where to find "libmysqlclient?"
I'm getting a traceback which says that the "libmysqlclient" interface package cannot be found – and indeed it can't be found where Python is looking: /usr/lib. It looks from preceding trace entries that it's using @RPATH as the source of where to look. But ... how does Python actually know "where to look for MySQL?" -
django update database everyday
I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I keep track of all the users scores and have a scoreboard shown on the site. If someone forgets to do the wordle that day I currently manually adjust there scores to reflect that but I would like to make it so this is done automatically. I have the site running on heroku currently. Not really looking for exact code but is there something easy to use that could run a program or something that allow me to check if a different field is null each day at midnight and if so save an input I have tried celery and I cant get it to install (wordleenv) kyleflannelly@MacBook-Pro-5 wordlegolfing % pip install django-celery Collecting django-celery Using cached django_celery-3.3.1-py3-none-any.whl (63 kB) Collecting celery<4.0,>=3.1.15 Using cached celery-3.1.26.post2-py2.py3-none-any.whl (526 kB) Requirement already satisfied: django>=1.8 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django-celery) (4.1) Requirement already satisfied: pytz>dev in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from celery<4.0,>=3.1.15->django-celery) (2022.2.1) Collecting kombu<3.1,>=3.0.37 Using cached kombu-3.0.37-py2.py3-none-any.whl (240 kB) Collecting billiard<3.4,>=3.3.0.23 Using cached billiard-3.3.0.23.tar.gz (151 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: asgiref<4,>=3.5.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) … -
Django passing context in JsonResponse
I am developing a webpage with filters to filter the results on the page. A Ajax is called, which sends the filters to my Django back-end. The results are filtered and the data should be passed back to the front-end. So now I need to pass my results of the models with context to the front-end. This leads to some problems. My Ajax: $(document).on('change', '#test-form', function (e) { e.preventDefault() var tags = []; $('input[name="tags[]"]:checked').each(function(i){ return tags[i] = $(this).val(); }); $.ajax({ type: 'POST', cache: false, url: "{% url 'core:jobSearch_nosearch' %}", data: { tags: tags, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function(data) { console.log('yey') console.log(data) } }); }); Here my View: from django.core.serializers.json import DjangoJSONEncoder from django.utils.functional import Promise class LazyEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Promise): return str(obj) return super().default(obj) def jobSearch(request, **search): companies = Company.objects.all() if request.method == 'POST': ads = Ad.objects.all() search_job = request.GET.get('search') if search_job: ads = Ad.objects.filter(title__contains=search_job) tag_filter = request.POST.getlist('tags[]') for tag in tag_filter: print(tag) ads = ads.filter(tag__name=tag) print(ads) context = {'companies': companies, 'ads': ads} # context = {'companies': list(companies)} # context = {'msg': 'Success'} # return JsonResponse(serialize('json', ads, cls=LazyEncoder), safe=False) return JsonResponse(context) else: ads = Ad.objects.all() context = {'companies': companies, 'ads': ads} return render(request, 'core/jobSearch.html', context) As you … -
cant show the category wise whats the problem?
enter image description here Here is the code I tried many ways but couldnt find any solution -
Heroku app successfully deploying, but receiving application error when loading site , please help to fix it
My logs don't indicate any errors as far as I can tell, but I'm receiving the following error when loading the site: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Below you can find the logs. Am I missing something here? 2022-11-18T17:15:57.358840+00:00 app[web.1]:time.sleep(0.1) 2022-11-18T17:15:57.358856+00:00 app[web.1]:File "/app/.heroku/python/lib/python3.10/sitepackages/gunicorn/arbiter.py", line 242, in handle_chld 2022-11-18T17:15:57.359058+00:00 app[web.1]:self.reap_workers() 2022-11-18T17:15:57.359074+00:00 app[web.1]:File"/app/.heroku/python/lib/python3.10/sitepackages/gunicorn/arbiter.py", line 525, in reap_workers 2022-11-18T17:15:57.359331+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2022-11-18T17:15:57.359539+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2022-11-18T17:15:57.580886+00:00 heroku[web.1]: Process exited with status 1 2022-11-18T17:15:57.719991+00:00 heroku[web.1]: State changed from starting to crashed 2022-11-18T17:16:10.573305+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=darazhar.herokuapp.com request_id=4a4e1fcd-e155-462e-8e2e-75b26cac0315 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:16:12.917542+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=darazhar.herokuapp.com request_id=a74a6a4f-15d0-4451-b4d1-1f6fbec726db fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:19:33.515138+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=darazhar.herokuapp.com request_id=2ea9b3e5-635c-4d3f-b419-2bbbb7523858 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https 2022-11-18T17:19:34.042904+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=darazhar.herokuapp.com request_id=c3c23553-a780-4527-ba81-bba249e5aee3 fwd="117.234.2.104" dyno= connect= service= status=503 bytes= protocol=https python django heroku -
Impossible export django-parler translated fields with the common comand dumpdata
Is there any way to dump and load data with a TranslatableModel because with the common python manage.py dumpdata app.Organization -o fixtures/organizations.json Django command translated fields do not appear in the file. models.py: class Organization(TranslatableModel, Entity): translations = TranslatedFields( name = models.CharField(verbose_name=_("Name"), max_length=200), description = RichTextField(verbose_name=_("Description"), blank=True, null=True, config_name='default') ) status = models.CharField(verbose_name=_("Status"), max_length=50), organizations.json: [ { "model": "app.organization", "pk": 1, "fields": { "status": "Active" } }, { "model": "app.organization", "pk": 2, "fields": { "status": "Active", } } ] Any idea ? Thanks in advanced. -
How Django rest IsAdminUser does not pass even the user is admin?
class Admin(models.Model): username = models.CharField(primary_key=True, max_length=30) password = models.CharField(max_length=255) email = models.EmailField(unique=True) created_on = models.DateTimeField(auto_now=True) django_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='admin') class AdminAPIViewSet(viewsets.ModelViewSet): queryset = Admin.objects.all() serializer_class = AdminSerializer permission_classes = [permissions.IsAdminUser] def get_queryset(self): if self.request.user.is_authenticated: return Admin.objects.filter(username=self.request.user.admin.username) else: return [] def create(self, request, *args, **kwargs): serializer = AdminSerializer(data=request.data) if serializer.is_valid(): email = serializer.data['email'] username = serializer.data['email'] password = serializer.data['password'] with transaction.atomic(): django_user = User.objects.create_user(username, email, password) admin = Admin.objects.create(**serializer.data, django_user=django_user) #User.objects.filter(pk=1001).update(is_superuser=True, is_staff=True) return Response(admin.pk) return Response('/error') class ClientFullAccessAPIViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer permission_classes = [permissions.IsAdminUser] def create(self, request, *args, **kwargs): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): email = serializer.data['email'] username = serializer.data['email'] password = serializer.data['password'] with transaction.atomic(): django_user = User.objects.create_user(username, email, password) client = Client.objects.create(**serializer.data, django_user=django_user) return Response(client.username) return Response('/error') `Here am trying to make the admin see the all the clients and the client see his data only ,... but I couldn't find why the i cant see the all the list clients as an admin, I am keep getting not authorized to access this endpoint.. ` urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers import user_management.views router = routers.DefaultRouter() router.register(r'clients', user_management.views.ClientReadOnlyAPIViewSet) router.register(r'clientslist', user_management.views.ClientFullAccessAPIViewSet) router.register(r'admin', user_management.views.AdminAPIViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', … -
Django Many2Many constraint
I am using Django with Django-Rest-Framework (no forms, no django_admin). I have the following models class Company(models.Model): ... class Sector(models.Model): ... company_id = models.ForeignKey(Company) employees = models.ManyToManyField(Employee) class Employee(models.Model): ... company_id = models.ForeignKey(Company) Employee can be in multiple Sectors and a Sector can have multiple Employees. (ManyToMany). I want to add a constraint employee.company_id == sector.company_id in order to add a record into the Many2Many table. I can do this validation in the serializers from the DRF, but I also want to handle this on the model level. I added a through table in the ManyToManyField class Sector(models.Model): ... company_id = models.ForeignKey(Company) employees = models.ManyToManyField(Employee, through='M2MTable') class M2MTable: ... def save(): # employee.company_id and sector.company_id validation is done here This will handle saving an M2MTable object, but however this will not handle related object references Sector.employees.add(Employee) From here I found out I can achieve this with m2m signals. Is there another way of handling this -
How to track mailto clicks in an email
I am sending emails via Mailgun using a django backend. Mailgun sends me back webhooks with information about url clicks in the email. However they do NOT ping me back about mailto clicks. I asked their support team and they confirmed this is expected behavior and they only track "urls"... which the mailto is not considered as. example: <a href="mailto:test@test.com"> Reply</a> How can i actually track mailto clicks in my email, what have people done in the past? I looked at the mailgun event logs and noticed none of the mailto clicks are registered. -
django-recaptcha error <urlopen error [Errno 11001] getaddrinfo failed>
*I implemented Google's reCAPTCHA to my site with the django-recaptcha plugin. All works well. But when I validate the captcha and launch the form I get this error <urlopen error [Errno 11001] getaddrinfo failed>. I would like to know how to interpret it and display a correct message to the user. Thanks in advance.* here is the error: URLError at /connexion/ <urlopen error [Errno 11001] getaddrinfo failed> Request Method: POST Request URL: http://127.0.0.1:8000/connexion/ Django Version: 4.1.2 Exception Type: URLError Exception Value: <urlopen error [Errno 11001] getaddrinfo failed> Exception Location: C:\Python310\lib\urllib\request.py, line 1351, in do_open Raised during: connexion.views.index_connexion Python Executable: C:\Users\User\Documents\Travail\sms-chapchap-2022\env\Scripts\python.exe Python Version: 3.10.4 Python Path: ['C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\src', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env', 'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env\\lib\\site-packages'] Server time: Fri, 18 Nov 2022 16:19:54 +0000 Connexion.Views : def index_connexion(request): if request.user.is_authenticated: return redirect('index_accueil') if request.method == 'POST': form = UserLoginForm(request.POST) email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if form.is_valid(): if user is not None: if user.is_active: auth.login(request, user) return JsonResponse(True, safe=False) else: messages.error(request, 'Votre compte n\'est pas activé, consultez vos Email!!') return JsonResponse(False, safe=False) else: messages.error(request, 'Email ou mot de passe invalide!') return JsonResponse(False, safe=False) else: for key, error in list(form.errors.items()): if key == 'captcha': messages.error(request, "Vous devez réussir le test reCAPTCHA") … -
Wrong model._meta.app_label (from other app) in Django database router
i have two different SQL databases and three apps in my django project. The apps are named PROD, TEST and common. I am trying to route everything that comes from an url of PROD to models.py from PROD and database1, and everything that comes from an url of TEST to models.py from TEST and database2. TEST -- models.py PROD -- models.py common It worked fine, until i introduced 'common'(after cloning the project to another folder) and i don't know why. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cfg_db_ic2_net_dev_test', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'proddb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cfg_db_ic2_net_dev_prod', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } DATABASE_ROUTERS = ['PROD.dbRouter.ProdDBRouter'] PROD/dbRouter.py: def db_for_read(self, model, **hints): "Point all operations on prod models to 'proddb'" from django.conf import settings print(model._meta.app_label) if model._meta.app_label == 'PROD': return 'proddb' return None ... PROD/views.py: def hosts(request): print("I did this") return render(request=request, template_name="common/hosts.html", context={"hosts": NetDefined.objects.all, "landscape": landscape}) The models.py for each TEST and PROD is pretty identical. The issue that i have is that the template hosts.html is populated with data from the default data base and not from proddb database. The reason for this is that the DBRouter … -
Extension "postgis" is not available even in postgis/postgis Docker image. [Django]
I'm building Docker image for my Django app. Tried both latest ubuntu and postgis/postgis base images with the following build step: RUN apt-get install --no-install-recommends -y --no-install-recommends \ python3 python3-pip wget gcc postgresql-15-postgis-3 postgresql-15-postgis-3-scripts \ libnewlib-arm-none-eabi avr-libc git libpq-dev libssl-dev libc6 gdal-bin When I run pytest I get the following error: self = <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7fa258c06e20> sql = 'CREATE EXTENSION IF NOT EXISTS postgis', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fa265a6f3a0>, 'cursor': <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7fa258c06e20>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.NotSupportedError: extension "postgis" is not available E DETAIL: Could not open extension control file "/usr/share/postgresql/15/extension/postgis.control": No such file or directory. E HINT: The extension must first be installed on the system where PostgreSQL is running.``` -
django .objects.values_list how to exlude None value
I'm using django .objects.values_list to get all the values of a filed of Model: def gen_choice(filed): return list(Mymodel.objects.values_list(filed, flat=True).distinct()) I want to exclude all the None value in the above query set : Mymodel.objects.values_list(filed, flat=True).distinct() Or the list: list(Mymodel.objects.values_list(filed, flat=True).distinct()) I have tried: def gen_choice(filed): return list(Mymodel.objects.exclude(filed=None).values_list(filed, flat=True).distinct()) Error: django.core.exceptions.FieldError: Cannot resolve keyword 'filed' into field. Choices are: -
Is it possible to expose a Django dev server running on a local machine to the public internet?
I'm new to Django and in trying to learn a little about running a server (firewall, permissions, ...) and deploying to production, I installed Ubuntu Server on an old laptop and connected it to my (wireless) router. I was able to set up port forwarding on the router, and to serve a static html page using nginx. I also bought a domain name and was able to change its DNS A record to point to my public IP address. This allowed me to go to mydomain.com and see my static html page. I tried to do something similar with the Django dev server but I could only access it on the local network. I set ALLOWED_HOSTS = ['*'] and ran the server on 0.0.0.0:8000 (after allowing incoming traffic on port 8000 using ufw on Ubuntu), and was able to access it from another computer on my local network by going to the local address 192.168.1.x. However, when I went to mydomain.com the page timed out. Is it possible in principle to achieve this? I know it's not a good idea to run a site this way but I only want to do it to learn and will allow access only … -
Applying DRY-principles to django: When to use class based views, when to use custom decorators?
I have an app consisting of function-based views. As the app is growing, I realize I need to implement DRY-principles in order to keep it manageable. The first thing I want to apply this to is a user status validation that is included with every view today: views.py def myview(request): user_profile = UserAccount.objects.get(user=request.user) if user_profile.type != "internal" and user_profile.type != "flex": if user_profile.duration < datetime.date.today(): return redirect('expired') If I understand it correctly, I can apply DRY here by building a custom decorator, or by building class-based views for my app - for example by extending a DetailView and building a base class for all my views around this. Are there any trade-offs to be aware of when choosing approach? I imagine class based views may be more scaleable in terms of applying DRY to other parts of the app, but the learning curve also seems a bit more steep in order to get to a point where it's actually working. -
Get the intersection of a django queryset with a __in
So I have an array and a queryset. some_array = [...] queryset = queryset.filter(some_field__in=some_array) Actually it returns every object that the "some_field" is in the array. What I want is only the objects that have all the fields from the array. Thx -
How I manage barbershop bookings based on length of service in Django
I'm supposed to manage barber salon bookings during the day based on length of service. For example: cut: 30 minutes cut + shampoo: 40 minutes There are multiple barbers in the salon. for now I have developed the barbershop and services models but I don't know how to implement the appointments and have them displayed for available time slots. class Barber(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) role = models.CharField(max_length=255) def __str__(self): return self.name + ' ' + self.surname class Service(models.Model): name = models.CharField(max_length=255) duration = models.PositiveIntegerField() price = models.FloatField() info = models.TextField(blank=True, null=True) def __str__(self): return self.name The appointment model I thought of implementing it in this way: class Appointment(models.Model): barber = models.ForeignKey(Barber, on_delete=models.CASCADE, related_name='appointments') service = models.ForeignKey(Service, on_delete=models.CASCADE, related_name='appointments') start_date = models.DateTimeField() name_client = models.CharField(max_length=255) client_email = models.EmailField() number_phone_client = models.CharField(max_length=10) def end_date(self): return self.start_date + timedelta(minutes=self.service.duration) But now I don't know how to manage the various slots available in a possible view based on the service and the barber chosen. -
AWS_QUERYSTRING_AUTH = False not working with cached AWS S3 images of public S3 bucket
I have a public AWS S3 bucket where I store mostly images for our site. I use boto3 to access and update images in the bucket. Usually, I wrap my calls to images in my templates in sorl thumbnail tags like so: {% thumbnail post.get_thumbnail_image.url '350x230' crop='center' as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}" alt="{{ post.title }}"> {% endthumbnail %} which results in the returned images looking like: https://mybucket.s3.amazonaws.com/cache/e4/8f/e48f5547cec7e4a869696527fac12a8f.jpg I now want to use Memcached to cache entire views on the website. I wouldn't think that would be a problem for a public bucket, because I don't expect the images requested to require a signature. Which is true once I set AWS_QUERYSTRING_AUTH = False in my settings.py - the images stop carrying signatures. The problem is though that even for a public bucket with AWS_QUERYSTRING_AUTH = False, the thumbnail files I get back throw an Access Denied error when the signatures are removed. Is this a matter of flushing some S3 cache somewhere? How can I make these cache thumbnail files respect my AWS_QUERYSTRING_AUTH = False? -
ModuleNotFoundError: No module named 'config.wsgi'
I'm trying to run a .py file and in the file I have this import from config.wsgi import * import os from django.template.loader import get_template from weasyprint import HTML, CSS from config import settings The whole project works, if I set runserver, the project starts without any problem, but this file does not work. The structure of the project is as follows NombreDelProyecto --app ---config ----__init__.py ----asgi.py ----settings.py ----wsgy.py ----db.py ---core ----general ----login ----user ----archivodetest.py the case as I say the project works, but in the views of the applications that I have been doing to put imports I get in red underlined but as I say it works for example: from core.general.forms import ActividadForm That comes out in red, if I put in front of the core, app.core as follows from app.core.general.forms import ActividadForm it does not show red but the project does not work and I get the following error from app.core.general.forms import ActividadForm ModuleNotFoundError: No module named 'app' I understand that it is the routes or something I did wrong from the beginning, please could someone help me. Thank you very much. I tried adding the route, changing the app's route in settings, but to no avail.