Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django - Passing in multiple parameters to Factory during testing
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). For this project, I'm working on functionality where a user will get an error if they try to invite someone who is already in the app (meaning people who are already in the app's database). I'm working on unit tests that ensures the error messages pop up when users are detected as already existing. I managed to get my first scenario working, but I'm a bit stumped for the second one. Here is a file that is central to both tests. factories.py class ChannelFactory(factory.django.DjangoModelFactory) class Meta: model = Channel id = int name = str class CurrentUserFactory(factory.django.DjangoModelFactory) class Meta: model = CurrentUser user_email = user_email channel = models.ForeignKey(Channel) Scenario #1 (currently working) - one new user is invited to join the app but already exists in the app's database test_forms.py from tests.factories import ChannelFactory, CurrentUserFactory @pytest.mark.django_db def test_that_current_user_cannot_be_reinvited(email, error_message): """user that is already in the specific channel cannot be reinvited""" email = "user@test.com" error_message = "user@test.com already exists in this channel" # I am not specifying the … -
What causes text to have an odd character at the end
I am using the django standard base.html with the following {% load i18n static %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" dir="{{ LANGUAGE_BIDI|yesno:'rtl,ltr,auto' }}"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Font Awesome CSS --> <script src="https://kit.fontawesome.com/5135d630a7.js" crossorigin="anonymous"></script> <title>{% block title %}{% endblock %}</title> This is giving me the following header with Home and Admin Pages having an odd character at the end. Is it the font? -
how to read json file array objets with python flask
I have a problem with read a file JSON, that file contains an array objects like this: [{"some": 1, "list": [{"one":1}]},{"some": 1, "list": [{"one":1}]}] my code is like below: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) show me this error: I try to read that file and put that file in ls_plano to read and assign to the other values like this: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) if ls_plano is not None: for plano in ls_plano: temp_plano = {} temp_plano["inPlanoPersonalizado"] = plano.get("inPlanoPersonalizado") temp_plano["inSelecionado"] = plano.get("inSelecionado") if plano.get("lsChassi"): temp_plano["lsChassi"] = self.__map_ls_chassi(plano.get("lsChassi", [])) if plano.get("lsTipoObjetoSegurado"): temp_plano["lsTipoObjetoSegurado"] = self.__map_ls_tipo_ob_segurado( plano.get("lsTipoObjetoSegurado") ) if plano.get("lsComissao"): temp_plano["lsComissao"] = self.__map_ls_comissao(plano.get("lsComissao", [])) if plano.get("lsParcela"): temp_plano["lsParcela"] = self.__map_ls_items(plano.get("lsParcela", [])) temp_plano["nmIdentificadorPlano"] = plano.get("nmIdentificadorPlano") temp_plano["nmPlano"] = plano.get("nmPlano") temp_plano["nrPlano"] = plano.get("nrPlano") temp_plano["vlAdicionalFracionamento"] = plano.get("vlAdicionalFracionamento") temp_plano["vlAssistenciaFacultativa"] = plano.get("vlAssistenciaFacultativa") temp_plano["vlCobranca"] = plano.get("vlCobranca") temp_plano["vlComercial"] = plano.get("vlComercial") temp_plano["vlIof"] = plano.get("vlIof") temp_plano["vlPremioLiquido"] = plano.get("vlPremioLiquido") temp_plano["vlPremioNet"] = plano.get("vlPremioNet") temp_plano["vlPremioTarifa"] = plano.get("vlPremioTarifa") temp_plano["vlPremioTotal"] = plano.get("vlPremioTotal") temp_plano["vlTotalComissao"] = plano.get("vlTotalComissao") temp_plano["vlTotalDesconto"] = plano.get("vlTotalDesconto") resp.append(temp_plano) return resp please help me, thanks for your attention. -
What does django's Manager.create() method do?
I was poking around in the rest_framework trying to figure out how it works, and came across a call to Model.objects.create(), but I can't for the life of me find the create() method for django model managers in the docs or the source code. It looks to be dynamically generated. What does it do, exactly? Where can I find its code? If I wanted to override it, what would my implementation have to do? I found this question but it only says to call the super().create() method. -
Django crispy form is not posting or view is incorrect
I am currently working on a note/comment system. It is intended to work as adding notes to each individual projects. For example, you set up a "Project" and there is a note or comment sections intended for adding updates to the project. Here is my view.py for updating the project. The top portion is for updating the project itself, the bottom portion is for adding the notes. @login_required(login_url="/login") def update_project(request, pk): queryset = DevProjects.objects.get(id=pk) form = UpdateProject(instance=queryset) if request.method == 'POST': form = UpdateProject(request.POST, instance=queryset) if form.is_valid(): form.save() return redirect('/') project = get_object_or_404(DevProjects, id=pk) notes = project.notes.filter(id=pk) new_note = None if request.method == 'POST': notes_form = AddProjectNotes(request.POST, instance=project) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.project = project new_note.save() else: notes_form = AddProjectNotes() return render(request, 'projects/updateprojects.html', {"form": form, "queryset": queryset, 'project': project, 'notes': notes, 'new_note': new_note, 'notes_form': notes_form}) Whenever I try and submit the notes, it shows that is successfully posted to DB but in DB there is no entries. Here is my template. <div class="container"> {% if new_note %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="post"> {{ notes_form.notes|as_crispy_field }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} </div> <div class="container"> … -
Django to Droplet: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I am getting Internal Server Error while setting up GNINX... On both the domain and on the droplet IP: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Correct response was give by: curl --unix-socket /run/gunicorn.sock localhost also sudo systemctl status gunicorn works as expected Gunicorn bind als worked on both the droplet IP and the domain. There is just something going on with GNINX. So I gues it has something to do with the file settings. Tried to reinstall the Droplet multiple times, Tried different settings and groups already, Nothing seems to work. -
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.