Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement sending a command from a page to Django via SSH?
How to implement sending a command from a page to Django via SSH? It is necessary that the page has a button that, when clicked, sends a command via SSH to the Ubuntu virtual machine. Good afternoon. Question regarding the implementation of SSH on pages in Django. It is necessary to assemble the command over SSH to the server. There is such code using Paramiko: views.py class StartServer(server, view): def get(self, request, *args, **kwargs): form = AddServerForm(request.POST or None) servers = server.objects.all() context = {'form': form, 'csservers': servers} return render(request, 'csservers/server_detail.html', context) # def post(self, request, *args, **kwargs): # pass def start_server(i, request, pc): print(request.POST) if request.POST: server = Server.objects.get(id=pk) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=server.host, username=server.server_username, password=server.secret, port=server.port) standard input, standard output, standard output = client.exec_command('./<command>') data = stdout.read() + stderr.read() client.close() HTML: <!DOCTYPE html> <html lang="en"> <head> <metacharset="UTF-8"> <title>Title</title> </head> <body> {{server.host}} {{server.port}} {{server.server_username}} {{server.secret}} <form action="{% url 'server_start' server.slug server.id %}" method="post"> {% csrf_token %} <button type="submit" style="outline: none; border: none; background-color: red; color: #fff;">Start server</button> </form> </body> </html> If I click on the button, it gives an error 405. I need to connect to the local Ubuntu machine via SSH and send the ./ command. Is it … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work with Firefox 107 or Chrome 107
With Firefox 107.0 in Win 10, in settings.py, I have SESSION_EXPIRE_AT_BROWSER_CLOSE = True In Storage in Firebug, I see the sessionid cookie with Expires/Max-Age: Session. When I close Firefox and restart it, the cookie is still there and so is my session information. I can manually delete the sessionid cookie. Is there something else I need to do or know? -
I keep getting "TypeError __init__() takes 1 positional argument but 2 were given" in my code but the urls and views are correct?
In Django, I am trying to create 2 new pages. I have created other pages using this similar approach. Here is my code for views.py and urls.py: views.py class practice_spanish(TemplateView): template_name = "practice_spanish.html" class quiz_spanish(TemplateView): template_name = "quiz_spanish.html" urls.py urlpatterns = [ re_path(r'^$', views.HomePageView.as_view(), name= 'home'), # Notice the URL has been named re_path(r'^about/$', views.AboutPageView.as_view(), name= 'about'), re_path(r'^chat/$', views.chat, name = 'chat'), re_path(r'^play/$', views.PlayPageView.as_view(), name = 'play'), re_path(r'^profile/$', views.ProfilePageView.as_view(), name = 'profile'), re_path(r'^scores/$', views.ScoresPageView.as_view(), name = 'scores'), re_path(r'^settings/$', views.SettingsPageView.as_view(), name = 'settings'), re_path(r'^practice_languages/$', views.Practice_languagesPageView.as_view(), name = 'practicelang'), re_path(r'^practicehtml/$', views.practicehtml, name = 'practicehtml'), re_path(r'^quiz_languages/$', views.Quiz_languages.as_view(), name = 'quiz_languages'), re_path(r'^quizhtml/$', views.quizhtml, name = 'quizhtml'), re_path(r'^practice_spanish/$', views.practice_spanish.as_view(), name = 'practice_spanish'), re_path(r'^quiz_spanish/$', views.quiz_spanish.as_view(), name = 'quiz_spanish'), path("chatrooms/<str:room_name>/", views.room, name="room"), path('admin/', admin.site.urls), re_path(r"^registration/$", views.registration, name = "registration"), re_path(r"^registration/register$", views.register, name = "register"), path("login_user", views.login_user, name="login_user"), path("index", views.home, name="home"), path("logout_user", views.logout_user, name="logout_user"), ] I am looking at practice_spanish and quiz_spanish. They are also named correctly as HTML files: my html files I tried to create 2 pages using the exact same way I created my others using the class-based views. I get an error this time when clicking on the buttons to take me to the 2 pages. -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
I have this APScheduler code: import atexit from apscheduler.schedulers.background import BackgroundScheduler from main.utils import run_employee_import scheduler = BackgroundScheduler() scheduler.add_job(run_employee_import, "interval", minutes=2) scheduler.start() # Shut down the scheduler when exiting the app atexit.register(lambda: scheduler.shutdown()) When I add this code to settings.py to run it when the app starts to run, it gives me the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error. -
How to use a Django (Python) Login Form?
I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login process canot work and the form is a simple static html form. I hope you can help me. HTML: <form class="windowlogscreen-content" method="POST" action={% url 'homepage' %}\> {% csrf_token %} <input type="text" placeholder="account" name="username"> <br> <input type="password" placeholder="password" name="password"> <br> <button style="margin: 20px;" type="submit">join</button> </div> </div> </form> views.py def loginuser(request): if request.method == "POST": username = request.POST\['accountName'\] password = request.POST\['accountPassword'\] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return views.homepage else: return redirect('start') else: return render(request, 'start', {}) -
Why is Django trying to find my image in such directory?
Instead"/media/", it tries to find here ??? The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong? models.py ` class Product(models.Model): name = models.CharField(max_length=255, verbose_name='Название товара') description = models.TextField(blank=True, verbose_name='Описание') price = models.DecimalField(max_digits=10, decimal_places=0, verbose_name='Цена') created = models.DateTimeField(auto_now_add=True, verbose_name='Время создания') updated = models.DateTimeField(auto_now=True, verbose_name='Время обновления') is_published = models.BooleanField(default=True, verbose_name='Публикация') available = models.BooleanField(default=True, verbose_name='Наличие') catalog = models.ForeignKey('Catalog', on_delete=models.PROTECT, verbose_name='Каталог') def __str__(self): return self.name def get_absolute_url(self): return reverse('product', kwargs={'product_id': self.pk}) class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" ordering = ['created'] class Images(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') images = models.ImageField(upload_to='images/%Y/%m/%d/') def __str__(self): return self.product.name ` admin.py ` class ImagesInline(admin.TabularInline): fk_name = 'product' model = Images @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ImagesInline, ] list_display = ('id', 'name', 'price', 'created', 'updated', 'is_published', 'available', 'catalog') list_display_links = ('id', ) search_fields = ('name', ) list_editable = ('name', 'price', 'is_published', 'available', 'catalog') list_filter = ('is_published', 'available', 'created', 'catalog') ` settings.py ` MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ` shop/urls.py ` urlpatterns = [ path('', index, name='home'), path('about/', about, name='about'), path('catalog/', catalog, name='catalog'), path('basket/', cart, name='cart'), path('register/', register, name='register'), … -
How to Run an ML model with Django and Celery
I have a Django project that uses a model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. views.py class BotView(GenericAPIView): serializer_class = BotSerializer def post(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() print(serializer.data) return Response(data=serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response(data=str(e), status=status.HTTP_400_BAD_REQUEST) serializers.py class BotSerializer(serializers.Serializer): questions = serializers.ListField(required=True, write_only=True) user_info = serializers.CharField(required=True, write_only=True) merchant = serializers.CharField(required=True, write_only=True) user_id = serializers.IntegerField(required=True, write_only=True) def create(self, validated_data): # call ai and run async upload_to_ai.delay(validated_data['questions'], validated_data['user_info'], validated_data['merchant'], validated_data['user_id']) return "successful" tasks.py @shared_task() def upload_to_ai(questions:list, user_info:str, merchant:str, user_id:int): model_predictions = predict(questions, BotConfig.MODEL, user_info) print(model_predictions) return Every time I send a request, the models begins to run as show my the image but it never goes past 0%. THIS BEHAVIOUR ONLY HAPPENS WHEN IT'S HOSTED BUT NEVER IN MY LOCAL. DOCKER IN MY LOCAL HAS THE SAME ISSUE. -
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.```