Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django upload file from the production area is not going to the folder I want
I got a problem. when I upload a file from admin area it goes to the correct folder and shows up correctly as I specified in the models.py : photo_service_1 = models.ImageField(upload to = 'photos_service/%y/%m/%d/', blank=True) but when I upload the file in production area it doesn't go to the correct path. thanks 4 helping me out. this is my html: and here is my related views.py: photo_service_1 = request. POST['photo_service_1'] contact.photo_service_1 = photo_service_1 -
django user profiles and different views
I'm building a CRM system and i want to have two types of users Administrator (More than 5 users) Supervisor (One person) Administrator will capture details in a django form, save it, and only have access to see their own work. A Supervisor will have a view of all Administrators captured work from the CRM, in a form of a list and all the of details the administrators. Question: How do i create two different types of users and how do i display the different types of views (Administrator = Their own work only, and Supervisor = All of the Administrators work). App One for users from django.db import models from django.contrib.auth.models import User # Create your models here. class UsersModels(models.Model): Role = [ ('Agent','Agent'), ('Manager','Manager'), ] TheUser = models.OneToOneField(User, on_delete=models.CASCADE) Rank = models.CharField(max_length=10, choices=Role, null=True) def __str__(self): return self.TheUser App Two from django.db import models from django.contrib.auth.models import User # Create your models here. class ExperimentalModels(models.Model): Name = models.CharField(max_length=12) Surname = models.CharField(max_length=12) created_by = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.Name Views is from django.shortcuts import render, redirect from . models import ExperimentalModels from . forms import ExperimentalForms from django.contrib import messages from django.contrib.auth.models import User # Create your … -
Django: CSRF verification failed. Request aborted. in production without domain name
I am running a Django app behind Nginx in a Docker environment. My problem is sort of the same from this thread: Django returning "CSRF verification failed. Request aborted. " behind Nginx proxy locally. Upon learning that I have to add CSRF_TRUSTED_ORIGINS in settings, since I am using Django version 4.X, I added my localhost CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', ] I can login to my admin when the container is deployed locally. However, when I deployed it to production, I still get the error: CSRF verification failed. Request aborted. I deployed it in a Google compute engine. The app does not have a domain name yet. Thus, I visit the app using its external address of the machine: http://XX.XX.XX.XX/admin. Should I add this address to my CSRF_TRUSTED_ORIGINS? My understanding is that this is the same as adding the localhost http://localhost since I am visiting the host machine's address. CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', 'http://XX.XX.XX.XX' ] What if I deployed it to another machine with a different address? Should I again add it? Is there any other way to allow the CSRF without specifically adding the address since it would be tedious if I would be changing/migrating in … -
Django Dockerisation with Mysql
Can Any one tell me how to dockerize django with mysql my django container is working fine independently & mysql but when I am trying to connect I am getting Connection Failed error , I can able to connect mysql via localhost when container is active can anyone help me with this. -
Disabling syntax highlighting in Python/Django Shell
With Django, you can start a Python shell in your project directory with python manage.py shell. Great, but can I disable that syntax highlighting somehow? Having every word colored some way makes it very hard to read anything. Removing termcolor.py as well commenting out every function of it fails, because django then can't import it and fails execution. The documentation sugggests that highlighting is not intended to be disabled. Is there no way to do this? -
Youtube API & Django integration
I have a function in Django that uses the youtube API to return the video_id, title and thumbnail_url based on the web_url that is provided by the user through the user create Video object form. The reason I did this was to make it easy for users to upload youtube videos to my app. def get_video_info(pk): print('get_video_info called') video = Video.objects.get(id=pk) web_url = video.web_url # Parse the video ID from the URL parsed_url = urlparse(web_url) query_params = parse_qs(parsed_url.query) video_id = query_params["v"][0] # Create a YouTube Data API client api_key = settings.YOUTUBE_API_KEY youtube = build('youtube', 'v3', developerKey=api_key) # Call the YouTube API to get the video details video_response = youtube.videos().list( part='id, snippet', id=video_id, maxResults=1 ).execute() # Extract the video details from the API response video_snippet = video_response['items'][0]['snippet'] thumbnail_url = video_snippet['thumbnails']['medium']['url'] title = video_snippet['title'] return { 'video_id': video_id, 'thumbnail_url': thumbnail_url, 'title': title, } I then have a signal function that triggers the get_video_info function when a Video object is created and then updates the Video fields with the return values of the function. @receiver(post_save, sender=Video) def create_video_info(sender, instance, created, **kwargs): print('create signal called') if created: # if the instance is being created video_id, thumbnail_url, title = get_video_info(instance.pk).values() instance.video_id = video_id instance.thumbnail_url = … -
How do I upload a local file to django-storages storage buckets?
I am trying to upload a file that is pre existing and has been modified on the server after upload, and then needs to be uploaded to the bucket. I created a custom storage, assigned it, and am trying to save with .storage.save(ContentFile). Is this the correct way to save a file already on the server to a bucket? Please let me know. Thank you. My code is as follows: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): bucket_name = 'mamasheen' file = models.FileField(storage=MediaStorage()) # to save the file, what I am asking about object.file.storage.save(filename, ContentFile(object.original_file.read())) -
List comprehension in django orm
How can I use list as filter in django orm better? I want to use some generator comprehension like (*data, sep=' | '), but don't now how to do it correctly here: data = [ { 'date': '2023-02-11', 'term': 1 }, { 'date': '2022-12-11', 'term': 3 }, { 'date': '2022-09-11', 'term': 6 }, { 'date': '2022-03-11', 'term': 12 }, ] result = TableName.objects.filter(Q(**data[0]) | Q(**data[1]) | Q(**data[2]) | Q(**data[3])) -
ModuleNotFoundError: No module named 'plotly' in Django
As you can see, I have successfully installed plotly in my Django project. (base) PS C:\Users\user\source\VVV\V_Project> pip list Package Version ---------------------------------- ------------------- plotly 5.13.1 However, it keeps showing the error. Traceback (most recent call last): File "c:\Users\user\source\VVV\V_Project\mysite\Plotly.py", line 3, in <module> from plotly.offline import plot ModuleNotFoundError: No module named 'plotly' My code is as follow. from django.shortcuts import render from plotly.offline import plot import plotly.graph_objs as go def index(request): x_data = [0,1,2,3] y_data = [x**2 for x in x_data] plot_div = plot([Scatter(x=x_data, y=y_data, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') return render(request, "plotly.html", context={'plot_div': plot_div}) I don't know why it cannot find the module plotly. Please help me. -
How to Implement Paytm Payment Gateway with Django?
I am trying to implement payment facility for my project and the code was working fine and now suddenly getting error. Thats what I get when I print the response. {'head': {'requestId': None, 'responseTimestamp': '1678521927424', 'version': 'v1'}, 'body': {'extraParamsMap': None, 'resultInfo': {'resultStatus': 'F', 'resultCode': '501', 'resultMsg': 'System Error'}}} Here is the code of which generate paytm checksum and return response. class InitiatePayment(APIView): def post(self, request, *args, **kwargs): paytmParams = dict() paytmParams['body'] = { "requestType" : "Payment", "mid" : PAYTM_MERCHANT_ID, "websiteName" : "DIYtestingweb", "orderId" : generate_order_id(), "callbackUrl" : "https://<callback URL to be used by merchant>", "txnAmount" : { "value" : "500.00", "currency" : "INR", }, "userInfo" : { "custId" : "nehatkn786@gmail.com", }, } checksum = paytmchecksum.generateSignature(json.dumps(paytmParams["body"]), PAYTM_SECRET_KEY) paytmParams["head"] = { "signature" : checksum } post_data = json.dumps(paytmParams) # for Staging url = f'https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid={PAYTM_MERCHANT_ID}&orderId={paytmParams["body"]["orderId"]}' response = requests.post(url, data = post_data, headers = {"Content-type": "application/json"}).json() print(response) # result = { # "txToken" : response["body"]["txnToken"], # "orderId": paytmParams['body']['orderId'], # "amount": paytmParams["body"]["txnAmount"]["value"], # } # return Response({'token':result['txToken'], 'orderId':result['orderId'], 'amout':result['amount']}, status=status.HTTP_200_OK) # return HttpResponse('Its working') return Response(status=status.HTTP_200_OK) The same code was working fine and was getting the transaction token. but suddenly getting error. Please help me out guys. -
File retrieve API in djangorestframework
I am trying to send a file from Frontend ( react ). I want to retrieve that file in Backend (Django) and save to database. I didn't find the correct way to retrieve my file from request object. Can any one help me how to write view function to retrieve the file in Django ? I sent file from frontend. I am trying to retrieve that file from request object in django. -
Impossible to import model_utils module in Django models.py
I follow the official documentation of the django-model-utils model and I've just done pip install django-model-utils in my virtual environment. However, VSCode indicates that Import "model_utils.managers" could not be resolved as shown below. VSCode error display With pip list I've checked that the module is effectively installed. Package Version ------------------------ -------- asgiref 3.6.0 autopep8 2.0.1 defusedxml 0.7.1 diff-match-patch 20200713 Django 4.1.5 django-admin-rangefilter 0.9.0 django-extensions 3.2.1 django-import-export 3.1.0 django-model-utils 4.3.1 django-phonenumber-field 7.0.2 djangorestframework 3.14.0 et-xmlfile 1.1.0 import-export 0.3.1 MarkupPy 1.14 odfpy 1.4.1 openpyxl 3.1.1 phonenumbers 8.13.4 Pillow 9.4.0 pip 22.0.2 pycodestyle 2.10.0 pytz 2022.7.1 PyYAML 6.0 setuptools 59.6.0 sqlparse 0.4.3 tablib 3.3.0 tomli 2.0.1 xlrd 2.0.1 And I've look that the folder exists with the right name and a __init__.py file as shown below. Screenshot of lib folders How can I solve this please ? -
django UniqueConstraint violation_error_message message not handled
I have this model: class DataMapping(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.CASCADE) department = models.ForeignKey(LocationDepartment, null=True, blank=True, on_delete=models.CASCADE) catagory = models.ForeignKey(CompanyCategory, on_delete=models.CASCADE) reason = models.ForeignKey(ReasonForProcessing, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint( name='unique_data_map', fields=['company', 'location', 'department', 'catagory', 'reason'], condition=Q(location__isnull=False), violation_error_message="This data map has already been added.", ), UniqueConstraint( name='unique_data_map_both_none_dep_none', fields=['company', 'location', 'catagory', 'reason'], condition=Q(department__isnull=True), violation_error_message="This data map has already been added." ), UniqueConstraint( name='unique_data_map_both_none', fields=['company', 'catagory', 'reason'], condition=Q(location__isnull=True) & Q(department__isnull=True), violation_error_message="This data map has already been added." ) ] with a basic modelform class DataMapForm(forms.ModelForm): class Meta: model = DataMapping fields = ( 'location', 'department', 'catagory', 'reason', ) widgets = { 'company': forms.HiddenInput() } and a view of: def data_mapping_new(request): company = get_current_logged_in_company(request) if request.method == "POST": form = DataMapForm(request.POST or None) if form.is_valid(): catagory = form.save(commit=False) catagory.company = company if form.is_valid(): form.save() I have a similar setup on a different model that works fine, but this one just raises an error django.db.utils.IntegrityError: duplicate key value violates unique constraint "unique_data_map_both_none" Should it not check the constraint at the first if form.is_valid(): What am I missing here? -
Django set homepage at http://127.0.0.1:8000
I made a chatbot with django framework, and I'm trying to deploy with heroku but it kept showing cannot be deployed, my app is working fine locally if i go to http://127.0.0.1:8000/chatbot/ but maybe if I set the homepage http://127.0.0.1:8000/ Heroku might be work so I wonder how should I change my urls.py to set my homepage as http://127.0.0.1:8000/ urls.py from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='home'), ] in templates folder i have one html file called index.html how should I change the code to set the homepage at http://127.0.0.1:8000/ views.py from django.shortcuts import render import openai openai.api_key = API_KEYS def chatbot(prompt): response = openai.Completion.create( model="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0 ) return response.choices[0].text.strip() def chatbot_view(request): chatbot_response = "" if request.method == 'POST': question = request.POST.get('question') chatbot_response = chatbot(question) return render(request, 'index.html', {'chatbot_response': chatbot_response}) I treid to change my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.chatbot_view), ] but it wasn't working -
Roles and Permissions between users and organizations
I'm building an application that allows users to belong to multiple organizations and can perform specific operations within each of these organizations as long as they have the required roles and permissions to do so. However, I kind of have issues implementing a satisfiable model that suits this requirement, especially given that roles and permissions in Django are typically related to the user's model and so it's impossible for them to vary with a particular user per organization. What I have done so far is implement a third model that records the role of a user with a particular organization in a separate table: class OrgUserPerms(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) user = models.ForeignKey("accounts.CustomUser", on_delete=models.CASCADE) user_role = models.CharField(max_length=25, choices=[ ("organization_admin","admin"), ("organization_manager", "manager"), ("organization_member", "member") ]) The problem with this model is that a user can have multiple OrgUserPerms referencing the same organization, I currently handle this by filtering the last saved OrgUserPerm object as the user's latest role in an organization then throw away the remaining OrgUserPerm objects with the same user&organization occurrence. I however feel this might eventually lead to operational bottlenecks in speed, security e.t.c and would deeply appreciate advice/suggestions from people with experience implementing something similar, thank you! -
How to add and fetch makrs to a subject which has foreignkey relation with class?
I want to add subject marks to specific classes of students. Where Subject has ManyToMany relation with Class and Class has ForeignKey relation with Student. class Subject(models.Model): name = models.CharField(max_length=50) mark = models.IntegerField(null=True, blank=True) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=30) subjects = models.ManyToManyField(Subject, blank=True) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=100) class_name = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name -
My django project on heroku cannot connect to postgresql
I am trying to alter the table of my database because i cannot migrate the changes in my models.py. I tried to connect to my database using command "heroku psql" or "psql + the needed url" but i keep receiving the error message "psql: error: connection to server at "ec2-3-211-6-217.compute-1.amazonaws.com" (159.100.251.128), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?" how to fix this? Thanks for the help in advance :) -
Not Found: /api/img/grid.png "GET /api/img/grid.png HTTP/1.1" 404 2468
Currently working on APIs using Django on VScode. Apis work fine, but every single time I access the urls this gets sent back to me. Didn't really try anything yet. I feel like there is a simple solution, but still beyond my abilities to find the problem. I have no images. I don't look to load images. Just working on some basic JSON apis using rest_framework. Debug tool shows nothing because the server runs fine. -
Auto increment on a dual unique constraint
I am trying to create a website using Django and MariaDB. here is my models.py file in my forum app. class Forum(models.Model): forum_name = models.CharField(max_length=30, unique=True) forum_date = models.DateTimeField('date_published', auto_now_add=True) class Topic(models.Model): forum = models.ForeignKey(Forum, on_delete=models.CASCADE) topic_order = models.IntegerField() topic_name = models.CharField(max_length=30) topic_exp = models.CharField(max_length=250) topic_date = models.DateTimeField('date published', auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['forum', 'topic_order'], name='topic_const') ] as you can see i have 2 models(Forum & Topic). and inside topic class i have this meta class which makes forum and topic_order a dual unique constraint. and here is my MariaDB Topic database id topic_order topic_name topic_exp topic_date forum_id 1 1 people 2023-02-26 16:23:50 1 2 2 jobs 2023-02-26 16:25:59 1 3 3 metal 2023-02-26 16:26:52 1 8 1 people 2023-02-27 13:03:32 2 11 2 jubile 2023-03-10 10:36:52 2 now all i want to is to make topic order an auto-increment field.for instance: if another forum_id=1 is added i want topic_order=4 to be added automatically.however if a forum_id=2 field is added the next topic_order must be 3. Has anyone ever seen something like that before? Thank you. I tried to make topic_order an auto-increment field with django's models.AutoField() class.but that didn't worked out. -
django template not rendering data
`i am writing a blog website and for every blog post i made a detail page template but it doesn't render any data **my views.py ** def Post(request ): posts=post.objects.all() context= {'posts':posts} return render(request, 'post.html', context) def detail(request,pk): posts=post.objects.all() context= {'posts':posts} return render(request, 'detail_page.html', context) my urls.py path('', views.Post, name='Post'), path('detail/int:pk', views.detail, name='detail'), post.html file {% for post in posts %} {{post.title}} - {{post.author}} {{post.body}} {% endfor %} ** my detailpage** {{post.title}}your text {{post.author}} {{post.body}} after rendering it just shows me a blank template` -
Django group_send messages are not sent instant
i am trying to build a lobby system for a game. I want the lobby to be startable and once started there should happen a countdown that is sent to each connected client. The problem is now that all messages are sent after the complete time has passed and not each second for the countdown. The weird thing for me is also, that the messages on the other client that are not the host are getting the message like they should (every second). I fell like the messages are grouped and then sent after all time is passed. PS: tried normal sent function and this is working like it should but i cant sent to other group members async def init_starting(self): if not self.lobby.status == "waiting": print("Already Started") return False else: print("Starting Countdown") #self.lobby.status = 'starting' #await self.save_lobby() await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started, 'host': self.host.username, 'players': self.players, 'lobby_code': self.lobby_code, 'countdown': 3}) countdown = 3 while countdown >= 0: countdown_data = { 'countdown': countdown } await self.send(json.dumps({"type": "msg", "message": countdown})) await self.send_status_message_with_status(status='starting', data=countdown_data) print(countdown) countdown -= 1 await asyncio.sleep(1) await self.send_status_message_with_status(status='started', data={ 'message': "Test" }) return True async def send_status_message_with_status(self, status, data): send_data = { 'type': 'status', 'status': str(status), } send_data = … -
Cannot delete record from ReactJS webpage, getting the error "method not allowed"
I am trying to make a React JS page that shows a list of appointments, and will delete the appointments if the Cancel/Finish buttons are clicked. However, I am getting the error "Method not Allowed." I have executed the same delete view in Insomnia's back-end and my delete view is working. Therefore, the problem is only in the ReactJS file. `import React, {useState, useEffect } from 'react'; function ListAppointments() { const [appointments, setAppointments] = useState([]) const getData = async () => { const response = await fetch('http://localhost:8080/api/services/'); if (response.ok) { const data = await response.json(); setAppointments(data.appointment) } } useEffect(()=>{ getData() }, []) const handleDelete = async (e) => { const url = `http://localhost:8080/api/services/${e.target.id}` const fetchConfigs = { method: "Delete", headers: { "Content-Type": "application/json" } } const resp = await fetch(url, fetchConfigs) const data = await resp.json() setAppointments(appointments.filter(appointment => String(appointment.id) !== e.target.id)) } return ( <div> <h1>Appointments</h1> <table className="table table-striped"> <thead> <tr> <th>VIN</th> <th>Customer Name</th> <th>Date</th> <th>Time</th> <th>Technician</th> <th>Reason</th> <th>Status</th> </tr> </thead> <tbody> {appointments.map(appointment => { return( <tr> <td>{ appointment.automobile.vin }</td> <td>{ appointment.customer}</td> <td>{ appointment.appointment_date}</td> <td>{ appointment.appointment_time}</td> <td>{ appointment.technician.name}</td> <td>{ appointment.reason }</td> <td> <button onClick={handleDelete} id={appointment.id} className="btn btn-primary" style={{backgroundColor:"red", border: '1px solid red'}}>Cancel</button> <button onClick={handleDelete} id={appointment.id} className="btn btn-primary" style={{backgroundColor:"green", border: '1px … -
reverse url django admin
small problem of Django and its reverse url, I try to have a link from a model to another model in the same admin:app I have this function to run reverse('admin:jobs_xml_jobboardexterne') I run from this page admin/jobs_xml/countjobboarderrors/ and I get an error: https://i.stack.imgur.com/Uf00J.png here the code was make the call : class CountJobBoardErrorsAdmin(admin.ModelAdmin): list_display = ("have_error_job_board", "have_not_error_job_board", "total_job_board") def have_error_job_board(self, obj): url = reverse('admin:jobs_xml_jobboardexterne') return mark_safe(f'<a href={url}>{JobBoardExterne.objects.count()}</a>') ok, so Django can't find my link, in my settings.py I have the application noted INSTALLED_APPS = [ ..., 'jobs_xml', ... ] my project urls.py also admin.autodiscover() urlpatterns = [ ..., url(r'^admin/', admin.site.urls), ] an idea ? I can't find the error. thank you for your help :) -
Unique together between field and model connected by ForeignKey django
I have two models. class Post(models.Model): title = models.CharField(max_length=150) class Attachment(models.Model): type = models.CharField(choices=AttachmentChoices.get_choices(), max_length=15) link = models.URLField() post = models.ForeignKey('Post', on_delete=models.PROTECT, related_name='attachments') I want to do something like this in meta class of Post model class Meta: unique_together = [('title', 'attachments')] but it dosn't work couse django can't find attachments field. Is there a solution provided by django that can solve this problem. -
Django Tinymce file tinymce.min.js not found
i am trying to integrate tinymce with a django app but django can't find the tinymce javascript file this is my settings.py : BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' MEDIA_URL = 'media/' STATICFILES_DIRS = [BASE_DIR/"staticfiles"] STATIC_ROOT = BASE_DIR/"static_root" MEDIA_ROOT = BASE_DIR/"media_root" #TinyMce TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tinymce/js/tinymce") TINYMCE_DEFAULT_CONFIG = { 'height' : 300, 'plugins': "image,imagetools,media,codesample,link,code,paste", 'cleanup_on_startup': True, 'menubar': True, 'toolbar': "styleselect |undo redo | bold italic | alignleft aligncenter alignright | link image media codesample code", 'image_caption': True, 'image_advtab': True, 'paste_as_text': True, 'custom_undo_redo_levels': 10, 'file_browser_callback' : "myFileBrowser" } and on localserver logs i have this : [10/Mar/2023 22:48:14] "GET /static/static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980 but i this it should be : [10/Mar/2023 22:48:14] "GET static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980