Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Have to run python manage.py collectstatic everytime I make change in my static files to show the changes in Django
I am creating a Django application and right now it's in development phase. I am using Google Cloud Storage, so I have to change settings accordingly, but after that I have to always run python manage.py collectstatic to show the changes in css or js file, no matter how small they are. settings.py STATIC_URL = 'static/' DEBUG = True DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'videovogue' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' service_account_key_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") GS_CREDENTIALS = service_account.Credentials.from_service_account_file(service_account_key_path) What is going wrong? MAX_FILE_SIZE = 209715200 # 200 MB -
How can I authenticate a user based on correct/incorrect credentials, but ignore their "is_active" state if I want to handle it separately?
Currently with django's default auth.authenticate method, it will return None if the credentials are correct, but user.is_active is false. This means that users who have correctly entered their credentials will receive the same error message as users who have incorrectly entered their credentials. I am looking to provide users with an error message for an edge case when they've entered the correct credentials, but haven't activated their account via email verification and thus user.is_active=False. My question is how do I implement this safely and efficiently? views.py: ... from django.contrib.auth import authenticate class LoginView(View): def get(self, request): return render(request, 'accounts/login.html') def post(self, request): username = request.POST['username'] password = request.POST['password'] if username and password: user = auth.authenticate(username=username, password=password) if user: if user.is_active: auth.login(request, user) return redirect('accounts:home') else: uidb64 = Base64.get_uidb64(user) message = format_html("Please check your email for a verification link, or <a href='{}'>click here to request a new one.</a>", reverse('accounts:verify', kwargs={'uidb64':uidb64})) messages.error(request, message) else: messages.error(request, 'Invalid account credentials. Please try again.') return render(request, 'accounts/login.html') return render(request, 'accounts/login.html') -
An error occurred (XMinioInvalidObjectName) when calling the PutObject operation: Object name contains unsupported characters
I've the following class class Foo: def value_to_filename(self, validated_data : dict): file_name = json.dumps(validated_data, cls=Encoder) file_name = self.convert_to_valid_s3_name(file_name) full_name = f"{file_name}.json" return full_name @classmethod def convert_to_valid_s3_name(cls, text : str): "value to cleaned filename" return base64.urlsafe_b64encode(text.encode()).decode() when uploading this to s3 it raises object name contains unsupported characters even if it doesn't measuring the name size it was less than 450 byte and max is 1024 so that can't be the issue but when splitting the name and using each half separately to check what part of the string is invalid, both halves worked perfectly example string: path/path/path/eyJhZGRsick12456IDEsICJtb2RpZmllZF9ieSI6IDEsICJjaGF0X2lkIjogIiIsICJjcmVhdGVkX2F0IjogIjIwMjotMDMtMjQgMjA6MjU6MjkuNzY1NzM0KzAwOjAwIiwgIm1vZGlmaWVkX2F0IjogbnVsbDwgInT4cGUQOiAic2FwZm9rYXBma2FwZnNkcFtsZnNkYVsgbGFmcGFkc29mIGthc1tvWyBscWVhLWZwIGRzW3BscjJbM3IncWUseHouZiwsengvZix6eCA7LGFzLGZhcydmIiwgImNhcmVQcm92aWRlciI6ICJhb3BrZmFwZiIsICJzdGFydF9kYXRlIjogIjIwMjQtMDMtMTQgMSQ6MTE6NDcuNjAxMDAwKzAwOjAwIn1=.json -
How can I optimize creating an xlsx file?
I have created an API that reads a file we recieve and then gives me back the information I need. I now need to create a new .xlsx file with this new data I have recieved. Currently it's working, but it is really not optimized. Creating a file with 4000 lines pretty much instant, but we will need to create files with up to hundreds of thousands of lines. At the moment, creating a file with 140,000 lines took 14 minutes. I am not very experienced in algoritm optimization so i'm not sure where look for optimizing. This is a project written with a Django backend. Here is the views.py function def vannmiljo(request): survey_id = request.GET.get('surveyID', None) if not survey_id: return JsonResponse({'error': 'SurveyID parameter is missing'}, status=400) instanceID = request.GET.get('m_instanceID', None) if not instanceID: error = "No datafile" return JsonResponse({'error': error}, status=400) instance = SurveyInstance.objects.get(id=instanceID) if not instance.survey_file: error = "No datafile" return JsonResponse({'error': error}, status=400) else: excel_file_url = instance.get_survey_file_url response = requests.get(excel_file_url) if not response.status_code == 200: print(f'Failed to download Excel file: {response.status_code}') excel_data = BytesIO(response.content) try: dfs = pd.read_excel(excel_data, engine="openpyxl") start_row = dfs[dfs.eq('Sal.').any(axis=1)].index[0] dfs = dfs.iloc[start_row:] dfs.reset_index(drop=True, inplace=True) dfs.columns = dfs.iloc[0] dfs = dfs[1:] data_list = [] columns_to_keep … -
Django returns AnonymousUser despite authenticating earlier
I have a problem where I call the login() function within Django and despite the user ID being set in the request session, whenever in another view I call request.user.is_authenticated which returns True. My login view: class LoginView(APIView): serializer_class = LoginUserSerializer def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): username = serializer.data.get('username') password = serializer.data.get('password') # If username is not present in the database at all user_exist_query = User.objects.filter(username=username) if not user_exist_query.exists(): return JsonResponse({"error": "Username does not exist"}, status = 401) # If username and password match user_auth_query = authenticate(username=username, password=password) if user_auth_query is not None: login(request, user_auth_query) return JsonResponse({"message": "Login Successful"}, status = 200) else: return JsonResponse({"error": "Username and Password combination is incorrect"}, status = 401) return JsonResponse({"error": "Bad Request"}, status=400) The other view where authentication actually works: class CheckAuthView(APIView): def get(self, request): if request.user.is_authenticated: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) I use this view to protect a route (using React as a frontend). The home page is only accessible to logged in users and whenever I am logged in, I am able to view that page and when I am logged out, a different page is showed therefore proving that here, getting the request.user does return an actual user. … -
Encountering "requires_payment_method" Error When Implementing Stripe Payment Method
I am encountering an issue while integrating the Stripe payment method into my website. The error message I'm receiving is "requires_payment_method". Below, I've provided the relevant JavaScript, HTML, and Python (Django) logic for handling payments. `<script> var stripe = Stripe('my_stripe_public_key'); function submitPaymentForm() { var cardholderName = document.getElementById('cardholder').value; var cardElement = elements.create('card'); stripe.createToken(cardElement).then(function(result) { if (result.error) { console.error(result.error.message); } else { document.getElementById('stripeToken').value = result.token.id; document.form_payment.submit(); } }); } </script>` ``` ` def checkout_payment(request): if request.method == "POST": payment_method_token = request.POST.get('stripeToken') print(payment_method_token) cardholder = request.POST.get('cardholder') cardnumber = request.POST.get('cardnumber') expiration_month = request.POST.get('mm') expiration_year = request.POST.get('yy') csc = request.POST.get('csc') # payment_type =request.POST.get('payment_type') user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) total = int(cart_total * 100) stripe.api_key = settings.STRIPE_SECRET_KEY try: customer = stripe.Customer.create( email = request.user.email, ) # Create PaymentIntent with retrieved payment method payment_intent = stripe.PaymentIntent.create( amount=total, currency='pkr', payment_method_types=["card"], customer=customer.id, description="Payment for items in cart", metadata={'integration_check': 'accept_a_payment'}, ) # Check for successful payment if payment_intent.status == 'succeeded': print(payment_intent) return redirect('checkout_complete') else: # Handle failed payment print(f"Payment failed with status: {payment_intent.status}") messages.error(request, 'Payment failed. Please try again.') except Exception as e: print(e) messages.error(request, 'An error occurred while processing the payment. Please try again.') return render(request, 'checkout_payment.html') Issue: … -
How to connect to Neo4J's AuraDB (free tier) from Django?
I have added the the following lines to my settings.py as follows: from neomodel import config import dj_database_url NEOMODEL_NEO4J_BOLT_URL = 'neo4j+s://xxxxxxx.databases.neo4j.io' NEOMODEL_SIGNALS = True NEOMODEL_FORCE_TIMEZONE = False NEOMODEL_ENCRYPTED_CONNECTION = False NEOMODEL_MAX_CONNECTION_POOL_SIZE = 50 user = 'neo4j' psw = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' uri = 'neo4j+ssc://xxxxxxxx.databases.neo4j.io' DATABASE_URL = 'neo4j+ssc://{}:{}@{}'.format(user, psw, uri) config.DATABASE_URL = 'neo4j+ssc://{}:{}@{}'.format(user, psw, uri) DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} And I get this error when I run python manage.py migrate: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "S_v1\venv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "S_v1\venv\lib\site-packages\django\core\management\__init__.py", line 382, in execute settings.INSTALLED_APPS File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\P\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "S_v1\mysite_2\mysite\settings.py", line 102, in <module> DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} File "S_v1\venv\lib\site-packages\dj_database_url\__init__.py", line 72, in config return parse( File "S_v1\venv\lib\site-packages\dj_database_url\__init__.py", line 126, in … -
Why are my Django project JavaScript files not loading, while the CSS files load successfully when they are both placed within the same static folder?
I am having issues to make my project load the Js files and functionalities. I am using this template from the internet. All of the static files (images, CSS and Js) are located inside the "static" folder but only Js is not loading. For example, the swiper and the data-aos are not working. #Base template {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Pezorium</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static 'img/favicon_fish_white.png' %}" rel="shortcut icon" type="image/png"> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500&family=Inter:wght@400;500&family=Playfair+Display:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/glightbox/css/glightbox.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/aos/aos.css' %}" rel="stylesheet"> <!-- Template Main CSS Files --> <link href="{% static 'css/variables.css' %}" rel="stylesheet"> <link href="{% static 'css/main.css' %}" rel="stylesheet"> <!-- ======================================================= * Template Name: ZenBlog * Updated: Jan 29 2024 with Bootstrap v5.3.2 * Template URL: https://bootstrapmade.com/zenblog-bootstrap-blog-template/ * Author: BootstrapMade.com * License: https:///bootstrapmade.com/license/ ======================================================== --> </head> <body> <header id="header" class="header d-flex align-items-center fixed-top"> <div class="container-fluid container-xl d-flex align-items-center justify-content-between"> <a … -
Django - Form for Editing Objects with a One-To-Many Relationship
I have a model which contains a variable length list of objects. I want to be able to edit this model in a form, and in the same form edit each of the associated objects in the list. I have looked at formsets which may be a way to handle the form for the multiple objects in the list, but from django documentation and searching online it is not obvious how I would then integrate this into the form of the parent object. What would be the best practice approach to this in Django? -
blank space on top and left of the page while developing frontend
I am building an application in Django and for writing templates I am using HTML/CSS, now there is some weird white space I am encountering on the top and left side of the page which does not go, no matter what I try as shown below now here are my css files base.css .navbar { position: fixed; top: 0; left: 0; width: 100%; height: 60px; display: flex; align-items: center; justify-content: space-between; background-color: #333; color: white; padding: 10px 20px; z-index: -1; } .navbar-brand img { max-height: 40px; } .navbar-menu ul { list-style-type: none; margin: 0; padding: 0; display: flex; } .navbar-menu li { margin: 0 10px; } .navbar-menu li a { color: white; text-decoration: none; } .navbar-user img { max-height: 30px; } and home.css .home-video { position: relative; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; } #bg-video { width: 100vw; height: 100vh; object-fit: cover; } .home-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } .home-content h1 { font-size: 3rem; margin-bottom: 20px; color: white; } .home-content p { font-size: 1.2rem; margin-bottom: 30px; color: white; } .btn { display: inline-block; padding: 10px 20px; background-color: #333; color: white; text-decoration: none; border-radius: 5px; transition: background-color 0.3s ease; } .btn:hover … -
Page not found when following wagtail tutorial adding tags
I wanted to add tags to posts in the quickstart Wagtail blog by following the (Wagtail tutorial). When I clicked the "foood" tag that I added to one of my posts, I ran into a Page not found (404) error. Check out the screenshot below Here is my class BlogTagIndexPage(Page) in blog/models.py # Add BlogTagIndexPage class BlogTagIndexPage(Page): def get_context(self, request): # Filter by tag tag = request.GET.get('tag') blogpages = BlogPage.objects.filter(tags__name=tag) # Update template context context = super().get_context(request) context['blogpages'] = blogpages return context and my blog_tag_index_page.html in blog/templates/blog/ {% extends "base.html" %} {% load wagtailcore_tags %} {% block content %} {% if request.GET.tag %} <h4>Showing pages tagged "{{ request.GET.tag }}"</h4> {% endif %} {% for blogpage in blogpages %} <p> <strong><a href="{% pageurl blogpage %}">{{ blogpage.title }}</a></strong><br /> <small>Revised: {{ blogpage.latest_revision_created_at }}</small><br /> </p> {% empty %} No pages found with that tag. {% endfor %} {% endblock %} What am I missing? -
Why my tags don't show not created in the form?
my list don't show the tags when i create an announcement outside admin panel, my tags don't show enter image description here my code: views @login_required def announcement_create(request): if request.method == 'POST': announcement_form = AnnouncementForm(request.POST) if announcement_form.is_valid(): instance = announcement_form.save(commit=False) #auto stand in field author his user name instance.author = request.user instance.slug = slugify(instance.title) announcement_form = instance announcement_form.save() messages.success(request, 'announcement created'\ 'succesfully') else: messages.error(request, 'Error create announcement') else: announcement_form = AnnouncementForm() return render(request, 'announcement/announc_create.html', {'announcement_form': announcement_form}) model: class Announcement(models.Model): category = models.CharField(choices=professions, blank=False) title = models.CharField(max_length=40, blank=False) slug = models.SlugField(max_length=250, unique_for_date='publish', ) price = models.IntegerField(default=None, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='announcement_work') publish = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=500, blank=False) company = models.CharField(max_length=30, blank=False) experience = models.CharField(choices=Experience, blank=False) address = models.CharField(max_length=30, blank=False) city = models.CharField(max_length=30, blank=False) country = models.CharField(max_length=30, blank=False) Favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Favorites', blank=True) class Meta: ordering = ['-id'] indexes = [ models.Index(fields=['-id']) ] def __str__(self): return self.title def get_absolute_url(self): return reverse('account:announcement_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) form: class AnnouncementForm(forms.ModelForm): class Meta: model = Announcement fields = ['category', 'title', 'price', 'country', 'city', 'description', 'experience', 'company', 'address', 'tags'] and i have another question: i don't know how to extract the announcement data to edit it and i've tried many ways, but i still … -
When I login to my heroku account,it is asking the code generated by authenticator app ,but I did not saved it when I login ..I can I solve this
When I login to my heroku it it is asking the code from authentication app I forget to save that code when I signup so it is getting an error when login,I now How can I get that code.. I want to login it ..I had tried it many times ,I unable to login it please any one help me to login it again , because I have to make some changes into my account please share the solutions please -
DefaultCredentialError in Django while using Google Cloud Services
I am building an application in Django where I am using Google Cloud Services for file upload and storage, but I am facing this error: in default raise exceptions.DefaultCredentialsError(_CLOUD_SDK_MISSING_CREDENTIALS) google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information. Here is my project directory structure: ├───core │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───core │ │ └───background │ ├───templates │ │ └───core │ └───__pycache__ ├───data ├───file_upload │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───file_upload │ ├───templates │ │ └───file_upload │ └───__pycache__ ├───users │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───users │ └───__pycache__ └───videovogue_web └───__pycache__ Now my .json file is in data folder, and here is my settings.py DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'videovogue' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "data/savvy-equator-418206-6d9e28bff3e9.json" ) If you guys need any other information, please tell me. Thanks -
VSCode task to run Django server and open Firefox
I'm trying to make a task that runs the Django server and opens Firefox. I've tried with { "version": "2.0.0", "tasks": [ { "label": "Django Server", "type": "shell", "command": "(python manage.py runserver &); sleep 10 && firefox http://127.0.0.1:8000", "group": { "kind": "build", "isDefault": true } } ] } The browser displays "Unable to connect". Refreshing the page doesn't help. Everything works fine if I run python manage.py runserver on the command line and then open http://127.0.0.1:8000 in Firefox manually. NOTE: everything works as expected when I switch firefox for chromium in the command field. -
Development Environment Django port 8000 to serve React (staticfiles)
I'm trying to setup a development environment for React and Django. https://github.com/axilaris/django-react <-- Here is my project code for reference. You can easily run in with the instructions below easily. Django (runs on port 8000) cd backend <-- to to this directory backend> python3 -m venv backendvirtualenv && source backendvirtualenv/bin/activate backend> pip install -r requirements.txt backend> python manage.py makemigrations backend> python manage.py migrate backend> python manage.py runserver React (runs on port 3000) cd frontend <-- to to this directory frontend> npm install frontend> npm run build frontend> npm start However, I'm trying to serve React staticfiles in Django so that I can run React on localhost:8000. In settings file: BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = [os.path.join(BASE_DIR, '../frontend/build/static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') and the I run backend> python manage.py collectstatic backend> python manage.py runserver However, when I point to my browser (http://localhost:8000/). It doesnt still have the React pages. How can I configure django so that I can run React and Django together in port 8000 ? -
Can I configure a free web app on Azure with static files?
I am trying to deploy my first Django project, but for some reason the static files are not working properly. When I check out static directory in my SSH it shows that the files are in there, but the template doesn't see them. My settings: STATIC_ROOT = BASE_DIR / "static" STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "assets" ] I couldn't find anymore answers on stack overflow that would help me so I asked chatGPT and he said that I should create a storage on Azure. When I asked him if there are free storage plans, he said no, but I shouldn't pay much and he forwarded me to pricing calculator which showed $21 for a month. This app has a funny static containing only of base.css and a mushroom photo. Should I really pay $21 or even more for it a month? I wonder if there is any other way than to create a storage or perhaps the pricing in the calculator was wrong. The code: https://github.com/JJDabrowski/Shroomcast -
Django 4.2 on Azure deployment: failure to load static
I am trying to deploy my first Django app to Azure and everything works, but for the static files. My settings: STATIC_ROOT = BASE_DIR / "static" STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "assets" ] The project doesn't have static directory while being added from the GitHub (https://github.com/JJDabrowski/Shroomcast), but this directory appears by itself after the deployment in the SSH in tmp/someStrangeString directory (someStrangeString looks like git commit name). And it's fully configured so I don't need to even run collectstatic in the folder. What am I doing wrong? -
Django NoReverseMatch Error: Reverse for 'course_detail' with arguments '('',)' not found
I'm encountering an issue with Django's URL reversing. Whenever I try to access the URL generated by the {% url 'course_detail' course.id %} template tag, I'm getting the following error: enter image description here Here's the relevant portion of my code: html enter image description here And here's how I've defined the URL pattern in my urls.py file: urls.py enter image description here I'm passing the course.id as the argument for the URL lookup, but it seems that it's not being recognized properly. Can anyone help me understand why this error is occurring and how I can resolve it? -
Loading static problem (Django 4.2. on Azure)
I am fighting with my first Django deployment on Azure and almost everything went smoothly now but for static files. I have read several threads about this, but I couldn't find the answer that would help me. I finished with this one for now, because it seemed the most logical: if DEBUG: STATICFILES_DIRS = [ BASE_DIR / "static" ] else: STATIC_ROOT = BASE_DIR / "static" But I get 500 on my site and even an SSH Console doesn't connect when I turn DEBUG=False even though deployment went smoothly. Without that if I got the error that the STATIC_ROOT cannot contain STATICFILES_DIRS. Some solutions suggest to set STATIC_ROOT to home/site/wwwroot, but it seems obsolete, since all the files are now located in tmp and some weird directory name that looks like git commit name or something like that, so it would be hard to set the root there. Repo: https://github.com/JJDabrowski/Shroomcast Please help :) -
Is there a way to create tables/entities on the Django db using RAW SQL
I would like to know whether it is possible to create and setup my entities in my database(db) using RAW SQL in my Django Project. I understand that we can use SQL Queries to handle entities that have already been created using ORM. Examples were shown in the Django Documentation I know that using RAW SQL is inefficient compared to using Django's ORM but one of the requirements of my project is to use SQL Statements for all database related functions. The following is the code written in models.py in my Django app: class Link(models.Model): name = models.CharField(max_length=50, unique=True) url = models.URLField(max_length=200) slug = models.SlugField(unique=True, blank=True) clicks = models.PositiveBigIntegerField(default=0) The following is an example of the SQL Statements needed to create my entity: CREATE TABLE Link ( id SERIAL PRIMARY KEY, name VARCHAR(50) UNIQUE NOT NULL, url VARCHAR(200) NOT NULL, slug VARCHAR(50) UNIQUE, clicks BIGINT DEFAULT 0 ); I can't seem to find any resources or any way to add my SQL Statements to my code using the Manager.raw(raw_query, params=(), translations=None) method. -
How to use djangorestframework-camel-case with drf-spectacular for camelcase schema
I have set up djangorestframework_camel_case and it works for rendered response data in swagger-ui (drf-spectacular) - camel case response is generated. But the schema generated in the swagger-ui is still snake-case. How can I make sure it also applies camel case to schema? I see this PR that apparently adds support for djangorestframework_camel_case, not sure exactly if it is expected to work out of the box, nothing in the docs. -
how can i put django-multi-captcha-admin in django jazzmin?
i was asking how can i put multi captcha admin in my Admin Login with Jazzmin which is Django Admin Theme??, because i've put the configs from multi captcha admin, but jazzmin doesn't allow me to show up the recaptcha in Login Admin Page i hope can you help me Thanks! i have this INSTALLED_APPS = [ 'jazzmin', 'multi_captcha_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django_recaptcha', 'captcha', ] MULTI_CAPTCHA_ADMIN = { 'engine': 'recaptcha', } JAZZMIN_SETTINGS = { # title of the window (Will default to current_admin_site.site_title if absent or None) obviously the captcha works when i remove the jazzmin from INSTALLED_APP, but when i'm in jazzmin, doesn't show it i don't know why.. i hope you can help me to fix it thanks! greetings -
Google Sheet Formula to Django Logic
I am creating a timesheet for an admin to enter time for users. I am converting this project from Google Sheets to Django. I am stumped to say the least. I am trying to get the total hours to match with the Google Sheet Formula. But it seems that my Django logic is not adding up. Here is the Google Sheet Formula: =(IF((MROUND(F6*24,0.25)-MROUND(F5*24,0.25))>=8,((MROUND(F6*24,0.25)-MROUND(F5*24,0.25)))-0.5,((MROUND(F6*24,0.25)-MROUND(F5*24,0.25))))) All cells (F5 and F6) are replaced with Start Time and End Time. Here is my Django logic. def calculate_total_time(self,start_time, end_time): if start_time is not None and end_time is not None: start_minutes = start_time.hour * 60 + start_time.minute end_minutes = end_time.hour * 60 + end_time.minute if end_minutes < start_minutes: end_minutes += 24 * 60 difference_minutes = end_minutes - start_minutes total_hours = difference_minutes / 60 # Calculate the rounded total hours rounded_hours = math.floor(total_hours * 4) / 4 # Adjust for cases where rounding might go over 8 hours if rounded_hours >= 8: rounded_hours -= 0.5 return rounded_hours else: return 0.00 Some hours display fine with no issues, but then I have hours like these where the logic does not add up. (Pictures for reference) Google Sheet Formula Output: Django Logic Output: I am trying to get the … -
why vercel return an error when deploying django app on it
I am endeavoring to deploy my Django application on Vercel following the method outlined in the video tutorial. However, during the build process, an error is being logged. Regrettably, I am unable to discern the cause of this error. Could someone proficient in this deployment process kindly pinpoint where I may have erred? The Logs: WARN! Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings Installing required dependencies... Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [21 lines of output] running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. …