Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i install mysql in vsc while in a venv when i get this error?
I have tried pretty much everything on here, github and other more shady website, but the venv wont install mysql in vsc. I have a django project where i cant connect to the mysql db. Using a macbook pro 2019, mysql is installed and running. I get this error: Collecting mysql Downloading mysql-0.0.3-py3-none-any.whl (1.2 kB) Collecting mysqlclient (from mysql) Using cached mysqlclient-2.2.1.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [27 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/builddjango/capstoneVenv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/builddjango/capstoneVenv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/builddjango/capstoneVenv/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/f2/kl4ptcws6p7_mn30tn5ktzk00000gn/T/pip-build-env-r64v109l/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/f2/kl4ptcws6p7_mn30tn5ktzk00000gn/T/pip-build-env-r64v109l/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/private/var/folders/f2/kl4ptcws6p7_mn30tn5ktzk00000gn/T/pip-build-env-r64v109l/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "", line 155, in File "", line 49, … -
unknown thread with unknown name gets created - Python
I'm creating a Django project in which I call threads to do some tasks for me. all the thread creation code I have is as below: thread = threading.Thread(target=check_businesses, name="startup_thread") crawl_thread = threading.Thread(target=crawl,name=f"crawl_thread_{username}",args=[username,POSTS_TO_CRAWL_COUNT,result_queue]) process_thread = threading.Thread(target=process_queue,name=f"procss_thread_{username}",args=[business,result_queue]) p_t = threading.Thread(target=handle_post,name=f"handle_post_{post.pk}",args=(post,)) m_t = threading.Thread(target=handle_media, name=f"handle_media_{m.pk}",args=(m,)) although these are all the threads I create when I do threading.enumerate() it gives me, among others, a thread with the name Thread-<n> (process_request_thread) where n is a number that gets increased everyt ime my startup_task is called. startp_task is the function in which I start startup_thread (check_business funciton) which in turn starts two new threads: crawl_thread and process_thread. Crawl thread starts crawling a website and stores the data in result_queue. process thread then reads items from this queue and stores their data in the database along with sending them to a remote server. The crawled data consists of a business, its posts and the medias of its posts. For sending each of these value I create a new thread. Also the remote server periodically calls an api which triggers crawling (basically calls startuo_task). that's all there is to it. I don't know and can't find out why it creates all these new threads. heres' a part … -
i won't to firebase_admin package in my cpanal and i face some error
Subject: Issue installing CFFI package with pip due to permission denied error Description: I'm encountering an error while attempting to install the CFFI package using pip in a virtual environment. The error message I'm receiving is: vbnet Copy code Error: command '/usr/bin/gcc' failed: Permission denied Failed to build cffi Could not build wheels for cffi, which is required to install pyproject.toml-based projects Steps taken: I'm working within a virtual environment named adminapp using Python 3.9. I've tried running pip install cffi but encountered the above error during the installation process. I've checked the permissions for the /usr/bin/gcc file, and they seem to be correct. Additional Information: Operating System: GUN/linux Python Version: 3.9 Pip Version: 23.3.2 Attempts to Resolve: I've tried running the installation with elevated privileges using sudo pip install cffi, but it didn't solve the issue. I've verified that the necessary build dependencies for CFFI are installed on my system. Request for Assistance: Could you provide guidance on how to resolve the permission denied error during the CFFI package installation process? Any insights or steps to troubleshoot and overcome this issue would be greatly appreciated. -
Who can help me with integrating Onlyoffice document server into a simple django python website? Perhaps I’ll pay for help or training
You need to create a standard django website (in docker, based on the base image of python 3.10) Postgresql database Write the necessary methods (views) to work with onlyoffice documentsserver Well, and accordingly integrate onlyoffice documentsserver (also in docker) Do everything via docker compose I tried but it didn’t work, I don’t understand -
How to hide the Page tab in the wagtail admin dashboard?
I am in the process of integrating wagtail with an existing Django project. For the time being, there is no need to use Pages, we will continue using Django Models for now. Is there any way to hide the Pages tab in the Admin? See screenshot below. Also if I am not leveraging Pages, are any of the wagtail apps below not needed? 'wagtail.contrib.forms', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail', -
Naive Python issue "No module named 'local_settings'"
I am using django as backend and trying to segregate the production settings and local settings by following steps here. I am facing following error when I do ./manage.py makemigrations, from local_settings import * ModuleNotFoundError: No module named 'local_settings' Following is what my settings.py looks like, # Set DEBUG based on the environment DEBUG = True if DEBUG: from local_settings import * else: from prod_settings import * local_settings.py and production_settings.py reside in the same directory as settings.py. Am I missing something? -
Password Reset Form missing in template with reseting in Django Rest Framework
I have a Django Project and there is an API app with Django Rest Framework. When the user tries to reset the button they receive the email with the link but when it is clicked the url shows only the reset button without the password reset form. Here is the urls.py router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') Here is the Django settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } AUTH_USER_MODEL = 'auth.User' REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'api.serializers.PasswordResetSerializer', } AUTHENTICATION_BACKENDS=['users.models.EmailBackend'] If I am using the default way to reset the password why is it showing a the password_reset_confirm.html without the form. I am sure the form is working as I tested it without DRF. -
Is it bad practice to create wagtail page only for organizational purposes?
I am in the process of migrating an existing Django app for a news website over to Wagtail. The first part of this migration will be porting all of the existing articles, that exist as Django models, over to Wagtail Pages. Along with this, we will have separate Wagtail Page types for website pages such as terms and conditions, privacy policy, etc. My question is the following, when looking that the Wagtail admin, it is clear that the articles need to be nested beneath a parent page for organizational purposes, otherwise all of the article pages will live amongst unrelated pages such as terms and conditions, privacy policy, etc... I have thus created a basic Page which is used only for organizational purposes, it is the parent for all Articles and lives at the HomePage level. class ArticleListing(Page): """A page meant for organizational purposes. All articles live under this page.""" max_count = 1 parent_page_types = ['news.HomePage'] subpage_types = ['news.Article'] The problem is that in order to register this page, it is given a url path. I do not want to return anything from this page at all, the url related to it should throw a 404. What should I do … -
How does CSRF validation work in Django and why do 2 different tokens still pass the check?
I'm currently reading up on CSRF and was wondering how is it possible for the CSRF validation in Django to validate 2 tokens as equal even if the values differ? if not _does_token_match(request_csrf_token, csrf_token): reason = self._bad_token_message("incorrect", token_source) raise RejectRequest(reason) This is the token check function, and it consists of: def _does_token_match(request_csrf_token, csrf_token): # Assume both arguments are sanitized -- that is, strings of # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS. return constant_time_compare( _unmask_cipher_token(request_csrf_token), _unmask_cipher_token(csrf_token), ) I've used the CSRF token that Django automatically generates and returns back in the response, and one which I generated manually with the get_token function from django.middleware.csrf and the result of _does_token_match is True. Not sure that I understand why is that. -
How to Ratelimit a URL path with wagtail?
I am in the process of migrating an existing django project to use wagtail CMS. I am unclear how I can ratelimit using wagtail, I see nothing about it in the documentation. Take the following example: Before integrating wagtail, I had a view which would return a privacy policy html page. This was ratelimited using redis, you can see the method decorator and method below @ratelimit( key='ip', rate='15/m', block=True ) def show_privacy_policy(request): context = base_context(request) return render( request, 'pages/privacy_policy.html', context ) Now this is removed, and I have a more generic wagtail Page which is used to render pages such as terms and conditions or privacy policy, I call this an InfoPage. The only thing I have defined is my InfoPage model which has a template path attached wagtail/info_page.html. class InfoPage(Page): template = "wagtail/info_page.html" last_modified_date = models.DateField("Last modified date") body = RichTextField(features=['bold', 'italic', 'link', 'ul', 'h3']) content_panels = Page.content_panels + [ FieldPanel('last_modified_date'), FieldPanel('body') ] parent_page_types = ['news.Index'] subpage_types = [] This simply just works, and all of my InfoPages are rendered correctly. However, I do not see any way to ratelimit access to these pages. If there is no way to ratelimit, I am susceptible to DDOS attacks and more. … -
Special char in url causes exception in daphne
On my local and the staging system one URL works with the special character (umlaut) but on our production system an exception is thrown: "Invalid characters in path - daphne" (https://github.com/django/daphne/blob/993efe62ce9e9c1cd64c81b6ee7dfa7b819482c7/daphne/http_protocol.py#L100) I use nginx as a reverse proxy in front of daphne. The staging system, as it should be, is basically the same as the production system, same nginx config and same daphne arguments etc. But I guess missed something. I do not know where else to look. The setup is: Django -> Daphne -> nginx -> AWS (ECS) -> EC2 Load Balancer. I checked both nginx configs and they are the same, except for the domain name. -
"Django Signal Issue: Calculating and Updating Montant_Total in Reservation Model with Assurance and Options
I'm using django 4.2 this is my models class Assurance(models.Model): nom = models.CharField(max_length=100) cout = models.DecimalField(max_digits=10, decimal_places=2) ordre = models.IntegerField(null=True, blank=True) def __str__(self): return self.nom class Option(models.Model): nom = models.CharField(max_length=255) description = models.CharField(max_length=255, null=True, blank=True) prix = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.nom class Reservation(models.Model): ETAT_CHOICES = [ ('en_attente', 'En attente de paiement'), ('paye', 'Paiement réussi'), ('annule', 'Réservation annulée'), ] utilisateur = models.ForeignKey(CustomUser, on_delete=models.CASCADE) voiture = models.ForeignKey(Voiture, on_delete=models.CASCADE) date_debut = models.DateField() date_fin = models.DateField() montant_total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, editable=False) assurance = models.ForeignKey(Assurance, on_delete=models.PROTECT, null=True, blank=True) options = models.ManyToManyField(Option, blank=True) ID_reservation = models.CharField(max_length=20, null=True, blank=True, editable=False, unique=True) date = models.DateTimeField(auto_now_add=True) etat = models.CharField(max_length=10, choices=ETAT_CHOICES, default='en_attente') ref_reservation = models.CharField(max_length=200, unique=True, blank=True, null=True, editable=False) this is my signal.py @receiver(pre_save, sender=Reservation) @receiver(m2m_changed, sender=Reservation.options.through) def update_montant_total(sender, instance, action=None , **kwargs): # Calculate the difference in days between the start and end date duree_reservation = (instance.date_fin - instance.date_debut).days + 1 # Calculate the total amount for the reservation based on duration and assurance cost montant_total = duree_reservation * instance.voiture.prix_journalier if instance.assurance: montant_total += instance.assurance.cout if action == 'post_add': # Calculate the total cost of selected options montant_option = instance.options.aggregate(total_price=Sum('prix'))['total_price'] or 0 montant_total += montant_option if action == 'post_remove' : montant_option = instance.options.aggregate(total_price=Sum('prix'))['total_price'] or 0 … -
Confirming whether an email exists or not
There are similar questions and I have already basically checked all of them. My question is when I try to clarify whether an e-mail really exists or not(such as test@test.com, I cannot clarify the same with my company email. The package I have used is py3-validate-email. Can anyone point me in the right direction for what I should do as the next step? I know that this tool checks for the regex as well, I have copied the code to receive any opinion. from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 from django.core.mail import send_mail from django.conf import settings import re from validate_email import validate_email def validate_email_address(email_address): return re.search(r"^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$", email_address) def contact_func(request, ): template = loader.get_template("contact_page/contact_page.html") context = { "contact":"contact_us", } if request.method == 'POST': message = request.POST['message'] email = request.POST['email'] name = request.POST['name'] if not validate_email_address(email): return HttpResponse("Invalid email address") is_valid = validate_email( email_address= email, check_format=True, check_blacklist=True, check_dns=True, dns_timeout=10, check_smtp=True, smtp_timeout=10, smtp_helo_host='smtp.gmail.com', smtp_from_address='my_mail.com', smtp_skip_tls=False, smtp_tls_context=None, smtp_debug=False, ) if not is_valid: return HttpResponse("Invalid email address") send_mail( name, #title message + '\nsend by ' + email, request.POST['email'], ['my_mail.com'], #receiver email fail_silently=False, ) return HttpResponse(template.render(context, request)) -
AttributeError: Manager isn't accessible via ... instances
Hi I'm adding comment section to my blog which are going to be lessons. For some reason I have this error: AttributeError at specific_lesson Manager isn't accessible via Lesson instances Error is reffering at the template: <form action="{% url 'lang_learning_app:lesson_detail' lesson.published.year lesson.published.month lesson.published.day lesson.slug %}" method="post" name="commentform" class="row comment-form"> I haven't received this error until now and I couldn't find example that is specific case to mine. urls.py path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'), views.py def lesson_detail(request, year, month, day, lesson): lesson = get_object_or_404(Lesson, status=Lesson.Status.PUBLISHED, slug=lesson, publish__year=year, publish__month=month, publish__day=day) #comments comments = lesson.comments.filter(hide_comment=False) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment=comment_form.save(commit=False) new_comment.lesson = lesson new_comment.author = request.user new_comment.save() return redirect(lesson.get_absolute_url()) #redirect here else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author':request.user}) else: comment_form = CommentForm() ....# other code return render(request, 'lessons/detail_lesson.html', {'lesson': lesson, 'similar_lessons': similar_lessons, 'comments':comments, 'new_comment':new_comment}) models.py class Comment(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='comments') comment = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) hide_comment = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment "{}" by {}'.format(self.comment, self.author.username) Thanks in advance! -
The feature names should match those that were passed during fit
Im trying to calculate the r squared value after the creation of a model using sklearn linear regression. Im simply importing a csv dataset filtering the interesting columns splitting the dataset in train and test creating the model making a prediction on the test calculating the r squared in order to see how good is the model to fit the test dataset the dataset is taken from https://www.kaggle.com/datasets/jeremylarcher/american-house-prices-and-demographics-of-top-cities the code is as following ''' Lets verify if there s a correlation between price and beds number of bathroom''' import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression df = pd.read_csv('data/American_Housing_Data_20231209.csv') df_interesting_columns = df[['Beds', 'Baths', 'Price']] independent_variables = df_interesting_columns[['Beds', 'Baths']] dependent_variable = df_interesting_columns[['Price']] X_train, X_test, y_train, y_test = train_test_split(independent_variables, dependent_variable, test_size=0.2) model = LinearRegression() model.fit(X_train, y_train) prediction = model.predict(X_test) print(model.score(y_test, prediction)) but i get the error ValueError: The feature names should match those that were passed during fit. Feature names unseen at fit time: Price Feature names seen at fit time, yet now missing: Baths Beds what am I doing wrong? -
Why is my Vue + Django Project still not allowing cors after proxy is setup?
I have a django + vue project Django http://localhost:8000 Vue http://localhost:8080 I set the devserver proxy as mentioned by most people and documentation but I'm still getting the error Proxy error: Could not proxy request /api from localhost:8080 to http://localhost:8000. 2024-01-02 12:03:14 See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED). vue.config.js const { defineConfig } = require("@vue/cli-service"); module.exports = defineConfig({ transpileDependencies: true, devServer: { proxy: "http://localhost:8000", }, }); and my axios request is axios .get("http://localhost:8080/api") .then((response: any) => (this.players = response)); I can share my repo if this isn't enough information. I've got just a basic django and vue setup, mostly from boilerplate so I haven't added anything that should interfere with this. I'm just really confused on why this isn't working. -
When does ManyToMany field get saved to the database?
Given the (simplified) model: class Appointment(models.Model): customer = models.ForeignKey(Customer, blank=False, null=True, on_delete=models.CASCADE) pianos = models.ManyToManyField(Piano, blank=True) I want to access 'pianos'. If it's a newly created Appointment, instance.pianos returns <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager object at 0x7f6f875209a0> and instance.pianos.all() returns an empty queryset, even though the pianos are displayed in the template form that was submitted to initiate the save. However, if it's an updating of an existing Appointment, 'pianos' returns the data as expected. Apparently that ManyToMany field doesn't get saved to the db immediately when save() is called. So how can I access the data in either of the methods below? def save(self, *args, **kwargs): # Is it a new Appointment, not an existing one being re-saved? newAppointment = self.id is None try: super().save(*args, **kwargs) # Call the "real" save() method. if newAppointment: # Returns empty queryset for piano in self.pianos.all(): print(piano) except: pass I also tried the alternative method of using a post_save signal, with exactly the same result: @receiver(signals.post_save, sender=Appointment) def createServiceHistory(sender, instance, created, **kwargs): if created: for piano in instance.pianos.all(): #empty queryset print(piano) The docs say that ManyToMany fields are saved using add() rather than save(), but I don't see how that would be applied in this case. -
When to use Class based view and Function based view in Django?
As I am learning Django, but I'm little bit confused about the class based view and function based view. Can you explain when to use them and what are the differences between them? -
I have problems connecting django with outlook
settings.py env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) # Configuración del backend de correo electrónico EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host y puerto del servidor de correo electrónico EMAIL_HOST = 'smtp.office365.com' #ejemplo: smtp.gmail.com, smtp.office365.com EMAIL_PORT = 587 # Configuración de TLS (Transport Layer Security) EMAIL_USE_TLS = True #False EMAIL_USE_SSL = False #True # Credenciales de autenticación del servidor de correo electrónico OUTLOOK_EMAIL = config('OUTLOOK_EMAIL') OUTLOOK_PASSWORD = config('OUTLOOK_PASSWORD') # Dirección de correo electrónico utilizada para enviar correos desde el sistema #DEFAULT_FROM_EMAIL = 'contacto@dessin.cl' FROM_EMAIL = config('OUTLOOK_EMAIL') views.py def contact(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') message = request.POST.get('message') # Configura los datos de Outlook remitente = email destinatario = os.getenv("OUTLOOK_EMAIL") clave_outlook = os.getenv("OUTLOOK_PASSWORD") # Configura el mensaje de correo electrónico email_message = f"Nombre: {name}\nCorreo: {email}\nTeléfono: {phone}\nMensaje: {message}" # Crea el objeto del mensaje email = EmailMessage() email["From"] = remitente email["To"] = destinatario email["Subject"] = "Nuevo mensaje de contacto desde el sitio web" email.set_content(email_message) try: # Configura el servidor SMTP de Outlook smtp = smtplib.SMTP("smtp-mail.outlook.com", port=587) smtp.starttls() # Imprime en la consola las credenciales y el mensaje print(f'Destinatario: {destinatario}, Mensaje: {email_message}') smtp.login(destinatario, clave_outlook) # Envía el mensaje smtp.sendmail(remitente, destinatario, email.as_string()) smtp.quit() # Muestra un mensaje de éxito … -
Static files on s3 of django project not being rendered in nginx server
I have stored the static files and media files in the S3 bucket and django project is stored in ec2 instance. I am using the nginx and gunicorn for server. The static files are being served in my local server but not in the nginx server. on local server but on the nginx server it gives 403 error server error Below is my sites-available/myproject file's code server { listen 80; server_name 54.226.78.2; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/project/BlueWays/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and below is the journalctl gunicorn log journalctl gunicorn and below is my gunicorn.service file code [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=ubuntu WorkingDirectory=/home/ubuntu/project/BlueWays ExecStart=/home/ubuntu/project/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ blueways.wsgi:application [Install] WantedBy=multi-user.target And Yes my S3 bucket is public and i also added CORS and Bucket Policy -
Creating a View that can handle a Form post and an Edit post
I am currently working with Django 5.0 and want to create a page that can handle both Form post and Edit post. I was able to get the view to handle this by using a try/except approach but I am running into the problem into formatting my url. I know that you need to be able to call the entry id in order to update a form post, but how do you pass that id in the form action? url path('test/', views.test, name='test'), views def test(request, log_id = None): log = Test.objects.all() if log_id == None: if request.method != 'POST': form = TestForm() else: form = TestForm(data=request.POST) if form.is_valid(): form.save() return redirect('home:home') else: if request.method != 'POST': form = TestForm(instance=log) else: form = TestForm(instance=log, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('test', args=[form.id])) context = { 'form':form, 'log':log, } return render(request, 'forms/test.html', context) -
How can I speed up hash comparison that seems to limited by lots of database calls?
I am dealing with a Django web app that needs to perform a hash comparison on +10M string hashes that are 64 characters long. I take the 100 most similar hashes and return them to the user; similarity is based on a hamming distance (number of characters that are the same). All of this happens in the backend of the Django server, which I suspect is not the best place to put this code. The basic workflow is this user makes a POST request -> passes through my views.py, which hashes the POST data -> hash is passed to below code. from hexhamming import hamming_distance_string from django.conf import settings import psycopg2 as pg import panadas as pd def _hamming_distance(hash1, hash2): return hamming_distance_string(hash1, hash2) def compare_image_hashes(hash): result_df = pd.DataFrame({'key': [], 'hash': [], 'difference':[]}) # Empty dataframe for all results MAX_CURSOR_PULL = settings.MAX_CURSOR_PULL # Max amount of results for the PG cursor SIMILARITY = settings.SIMILARITY # Value to determine if an image is similar LIMIT = settings.LIMIT conn = pg.connect( database=settings.DATABASE['DATABASE_NAME'], user=settings.DATABASE['DATABASE_USER'], password=settings.DATABASE['DATABASE_PASSWORD'], host=settings.DATABASE['DATABASE_HOST'], port=settings.DATABASE['DATABASE_PORT'] ) cursor = conn.cursor('hash-cursor') cursor.itersize = LIMIT # Redudant limit query = "SELECT hash, key FROM hashes LIMIT %s;" % LIMIT cursor.execute(query) chunk = cursor.fetchmany(MAX_CURSOR_PULL) columns = … -
How to Access Pytest Fixtures passed into Pytest Classes with the pytest.mark.usefixture marker
I wrote a base test class to be used to test multiple viewsets that all depended on different fixtures, this meant i did not want to directly pass in the fixtures into the test class methods as arguments and need to pass the fixtures as the class level for each of the subclass of the base test class, but doing so has prevented easy access of the fixture as a class/instance attribute in the class methods. this is a snippet of the base test class class BaseViewSetTest(TestHelper): """ Base Mixin Test Class to make testing viewset endpoints enjoyable. inherit the class in the test class you wish to use for a viewset, provide the base_url for the viewset and the create_data needed to make a post request to create a data instance linked to the viewset, provide the api_fields list exposed by the serializer of the viewset. """ base_url = "" create_data = {} api_fields = [] def test_list_endpoint(self, authenticated_user: tuple[User, APIClient]): user, client = authenticated_user url = reverse(f"{self.base_url}-list") response: Response = client.get(url) assert response.status_code == 200 response_data = response.json() # more tests goes here.. @pytest.mark.django_db @pytest.mark.usefixtures("business") class TestBusinessViewSet(BaseViewSetTest): base_url = "business" create_data = {"name": "InfoSec", "email": "ema@gmail.com", "phone_number": "09037637633"} … -
creating certificates with django
I'm building an edutech site where after a user has completed a course and its quizzes it generates a certificate using an existing template. I plan on collecting the users first name, last name from the user model, the date the certificate was created certificate template and then apply it on the certificate. I've written the logic up to some point but I still need help class get_score(APIView): def get(self, request, quiz_id=None, *args, **kwargs): user = self.request.user data = {} total_score = 0 total_possible_score = 0 try: main_quiz = MainQuiz.objects.get(id=quiz_id) quiz = main_quiz.quizzes.all() for individual_quiz in quiz: total_possible_score += individual_quiz.question.count() scores = Score.objects.filter(user=user, quiz__in=quiz) for score in scores: total_score += score.total score.total = 0 score.save() UserAnswer.objects.filter(score=score).delete() threshold = total_possible_score * 0.5 data['total'] = total_score data['possible_score'] = total_possible_score if total_score >= threshold: FONT_FILE = ImageFont.truetype(r'font/KaushanScript-Regular.otf', 180) FONT_COLOR = "#FFFFFF" template = Image.open(r'certificates/cert1.png') WIDTH, HEIGHT = template.size first_name = user.first_name last_name = user.last_name name = first_name + " " + last_name image_source = Image.open(r'certificates/cert1.png') draw = ImageDraw.Draw(image_source) name_width, name_height = draw.textsize(name, font=FONT_FILE) draw.text(((WIDTH - name_width) / 2, (HEIGHT - name_height) / 2 - 30), name, fill=FONT_COLOR, font=FONT_FILE) cert = certificate.objects.create(user=user, image_fmt=image_source) message = {'message': 'You have successfully completed your course.', 'img_certificate': cert.image_fmt, … -
How to return multiple values from Subquery as an Array using Django ORM
For example I have this model: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) value = models.IntegerField() p1 = Parent.objects.create(name='parent1') c1 = Child.objects.create(parent=p1, value=1) c2 = Child.objects.create(parent=p1, value=2) c3 = Child.objects.create(parent=p1, value=3) I want to make a subquery to behave like this: parents_with_children = Parent.objects.annotate( child_values=ArrayAgg('child__value', filter=F('child__parent_id') == F('id')) ) for parent in parents_with_children: print(f"Parent: {parent.name}, Child Values: {parent.child_values}") OUTPUT: ## Parent: parent1, Child Values: [1, 2, 3]