Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an import-export using Rest Framework in Django?
I don't know how to create the import-export an excel file using the Rest Framework in Django. I haven't seen any article and any tutorial that related on import-export rest framework. Here is my html code in import Asset List Import \ \ \ <div class="content-wrapper"> <section class="content"> <div class="row"> <div class="col-sm-6"> <h4 class="font-weight-bolder">Asset List Import</h4> </div> </div> </section> <section class="content pb-4"> <div class="row"> <div class="col-12 col-sm-12"> <div class="card"> <div class="card-header d-flex align-items-center px-3 py-2"> <div class="card-title"> Import file </div> </div> <div class="card-body"> <div class="col-md-6 offset-md-3 mt-5"> <div class="card"> <div class="card-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="file">Choose CSV file</label> <input class="form-control col" type="file" name="file" accept=".csv, .xlsx"> </div> <button type="submit" class="btn btn-cyan mt-3">Import</button> </form> </div> </div> </div> </div> </div> </div> </div> <!--Start Card Footer ---> <div class="card-footer float-end"> <a class="btn btn-outline-cyan" href="{% url 'asset_list' %}">Cancel</a> </div> <!--End Card Footer ---> <section> </div> I want this import will function and I can import-export an excel file. -
Django rest how to serializers all child comment under it's parent comment
Now my API response look like this "results": [ { "id": 12, "blog_slug": "rest-api-django", "comment": "Parent Comment", "main_comment_id": null }, { "id": 13, "blog_slug": "rest-api-django", "comment": "Child Comment of 12", "main_comment_id": 12 }, { "id": 14, "blog_slug": "rest-api-django", "name": "Mr Ahmed", "comment": "Child Comment OF 13", "comment_uuid": "c0b389bc-3d4a-4bda-b6c6-8d3ef494c93c", "main_comment_id": 13 } ] I want something like this { "results": [ { "id": 12, "blog_slug": "rest-api-django", "comment": "Parent Comment", "main_comment_id": null, "children": [ { "id": 13, "blog_slug": "rest-api-django", "comment": "Child Comment of 12", "main_comment_id": 12, "children": [ { "id": 14, "blog_slug": "rest-api-django", "name": "Mr Ahmed", "comment": "Child Comment OF 13", "comment_uuid": "c0b389bc-3d4a-4bda-b6c6-8d3ef494c93c", "main_comment_id": 13 } ] } ] } ] } so each child will be under its parent. here is my mode class BlogComment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) blog_slug = models.CharField(max_length=500) main_comment_id = models.ForeignKey("self",on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=250) email = models.CharField(max_length=250) comment = models.TextField() is_published = models.BooleanField(True) comment_uuid = models.CharField(max_length=250) my BlogCommentSerializers class BlogCommentSerializers(serializers.Serializer): id = serializers.IntegerField(read_only=True) comment_uuid = serializers.CharField(read_only=True) blog_slug = serializers.CharField(max_length=500) main_comment_id = serializers.CharField(required=False) name = serializers.CharField(max_length=250) email = serializers.CharField(max_length=250) comment = serializers.CharField(style={'base_template': 'textarea.html'},allow_blank=False,required=True) is_published = serializers.BooleanField(default=True) def to_representation(self, instance): data = { 'id': instance.id, 'blog_slug': instance.blog_slug, 'name': instance.name, 'email': instance.email, 'comment': instance.comment, "comment_uuid": instance.comment_uuid, "main_comment_id": instance.main_comment_id } if instance.main_comment_id: … -
Django logging output that doesn't seem to be part of root
I'm trying to understand Django's logging output so I've separated out all the core django loggers (django, django.request, django.db.backend, core, django.template) and set their levels to WARNING and gave it it's own formatter to make it more easily distinguishable from the rest. I've also overridden the root logger, set it to debug and made a similar easy to notice formatter for it. So now I get stuff like this: 127.0.0.1:99999 - - [08/Nov/2023:00:50:06] "GET /static/frontend/main.js" 304 - ROOT CRAP ! >>>>>>> [2023-11-07 16:50:10] - daphne.http_protocol - HTTP response complete for ['127.0.0.1', 99999] 127.0.0.1:99999 - - [08/Nov/2023:00:50:10] "GET /api/auth/user" 200 606 ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP 200 response started for ['127.0.0.1', 99999] ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP close for ['127.0.0.1', 99999] ROOT CRAP ! >>>>>>> [2023-11-07 16:50:12] - daphne.http_protocol - HTTP response complete for ['127.0.0.1', 99999] 127.0.0.1:99999 - - [08/Nov/2023:00:50:12] "POST /sg/query/user_tasks" 200 6001 But I still don't know where those REST logs are originating from (ie the ones that don't say ROOT CRAP!). I assumed they'd be a part of the root log stream but apparently they aren't? Is there another Django-level logger that I've not accounted for. These are … -
Can you help me ? my application display an error (500)
I have a problem: my django application display an error 500. I rolled back to a version that is working on heroku, pull the code, but when i push just by changing a in my html file into heroku, i got again an error 500, the logs telling me anything. Someone got an idea about what's going on ? Thank u by advance ! Rolled back, pull the code and i was expecting that works -
How to run some vps together with database in another server?
I need to run django site and some scripts together on vps server. But scripts has a large load on the server. Therefore, I assume creating 4 VPS, 1 for the site, the second for the database and the remaining 2 for scripts. And i need to somehow connect them to the database. What technology can be used to achieve this? As I understand it, large companies use several servers to distribute loads, I want to do the same. I only have experience installing Django with postgresql on Nginx with Gunicorn on one vps -
failed to authenticate multiple user in django
I have multiple user models in my Django app, one for OLAROOM and the other one for REALTOR. As you can see, everything is working successfully, but when I try to authenticate them and redirect them based on their role, it does not work. The authentication is working fine, but instead of redirecting the Olaroom user to the Rooms page, it is redirecting me to the Realtor_Dashboard, and the user role isn't a Realtor. Using the form below, the user is created based on what is defined in the save function. However, when I try to authenticate them and redirect the user to the page based on their role, it doesn't work, and I'm using the same method, something like this: user.Role.REALTOR and user.Role.OLAROOM. How can I solve this problem please? def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.Role.REALTOR: auth_login(request, user) return redirect('Realtor_Dashboard') elif user.Role.OLAROOM: auth_login(request, user) return redirect('Rooms') else: messages.error(request, 'Invalid Creadentials') else: form = AuthenticationForm() return render(request, 'Login/login.html', {'form':form}) User Models class User(AbstractUser): class Role(models.TextChoices): ADMIN = "ADMIN", 'Admin' REALTOR = "REALTOR", 'Realtor' OLAROOM = "OLAROOM", 'Olaroom' base_role … -
Django WSGI with Gunicorn does not find settings
I am following the tutorial to dockerize a django application with associated github code. My problem is when I try to start the application using gunicorn, the application = get_wsgi_application() line of wsgi.py fails with: [2023-11-07 20:05:13 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2023-11-07 20:05:13 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2023-11-07 20:05:13 +0000] [1] [INFO] Using worker: sync [2023-11-07 20:05:13 +0000] [37] [INFO] Booting worker with pid: 37 [2023-11-07 20:05:13 +0000] [37] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/mpp/mpp/mpp/wsgi.py", line 20, in <module> application … -
Custom token authentication with Django and Firebase
Sure, here's a sample Stack Overflow question for the problem of custom token authentication with Django and Firebase: Title: Custom token authentication with Django and Firebase Problem: I'm trying to implement custom token authentication with Django and Firebase. I've followed the steps in the documentation, but I'm still having trouble getting it to work. When I try to sign in with the custom token, I get an error that says "Invalid custom token." `# Django server code from django.contrib.auth import authenticate, login from rest_framework import permissions, views, status from firebase_admin import auth class CustomTokenLogin(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'error': 'Missing username or password'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if user is not None: login(request, user) # Create a custom token using Firebase Admin SDK custom_token = auth.create_custom_token(user.uid) return Response({'token': custom_token}) else: return Response({'error': 'Invalid username or password'}, status=status.HTTP_401_UNAUTHORIZED) for verify token ' class ProfileView(APIView): def get(self, request): try: decoded_token = auth.verify_id_token(request.headers.get('Authorization', '')) user_id = decoded_token['uid'] user = User.objects.get(id=user_id) # Fetch the user from the database # Fetch user profile data profile_data = { 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name # Include … -
Custom Django Model User
I can´t seriualize this class : class RidesSerializer(serializers.ModelSerializer): passageiros = CarregaDadosPassageirosSerializer(many=True, required=False,read_only=True) passageiros_id = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=User.objects.all(),source='passageiros') class Meta: model = Ride fields = ['motorista','passageiros','passageiros_id','data_publicaçao', 'data_saida','origem','destino','preço','veiculo','modalidade'] wich brigs this other class , 'CarregaDadosPassageirosSaerializer', and i need to extend a field to the model User : class CarregaDadosPassageirosSerializer(serializers.ModelSerializer): class Meta: diretorio = serializers.ImageField(source='user.profile.diretorio',read_only=True) nome_usuario = serializers.SerializerMethodField() model = User fields = ['id','username','email','diretorio'] def get_nome_usuario(self, obj): return obj.nome.username The error in the output i´ve been receiving everytime is the following : 'Field name diretorio is not valid for model User'. So, how can i fix this ? I've tried changing some aspects in models.accounts : user = mo.OneToOneField(User,related_name='userprofile',on_delete=mo.CASCADE) -
Failed building wheel for twisted-iocpsupport
I'm trying to dockerize my django project. When i run "docker build -t django_project" i get following error: 18.82 Building wheel for twisted-iocpsupport (pyproject.toml): started 19.23 Building wheel for twisted-iocpsupport (pyproject.toml): finished with status 'error' 19.24 error: subprocess-exited-with-error 19.24 19.24 × Building wheel for twisted-iocpsupport (pyproject.toml) did not run successfully. 19.24 │ exit code: 1 19.24 ╰─> [13 lines of output] 19.24 running bdist_wheel 19.24 running build 19.24 running build_ext 19.24 building 'twisted_iocpsupport.iocpsupport' extension 19.24 creating build 19.24 creating build/temp.linux-x86_64-cpython-39 19.24 creating build/temp.linux-x86_64-cpython-39/twisted_iocpsupport 19.24 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Itwisted_iocpsupport -I/usr/local/include/python3.9 -c twisted_iocpsupport/iocpsupport.c -o build/temp.linux-x86_64-cpython-39/twisted_iocpsupport/iocpsupport.o 19.24 twisted_iocpsupport/iocpsupport.c:1210:10: fatal error: io.h: No such file or directory 19.24 1210 | #include "io.h" 19.24 | ^~~~~~ 19.24 compilation terminated. 19.24 error: command '/usr/bin/gcc' failed with exit code 1 19.24 [end of output] 19.24 19.24 note: This error originates from a subprocess, and is likely not a problem with pip. 19.24 ERROR: Failed building wheel for twisted-iocpsupport 19.24 Successfully built autobahn 19.24 Failed to build twisted-iocpsupport 19.24 ERROR: Could not build wheels for twisted-iocpsupport, which is required to install pyproject.toml-based projects 19.70 19.70 [notice] A new release of pip is available: 23.0.1 -> 23.3.1 19.70 [notice] To update, run: pip … -
Dynamically add select fields Django form
I have a model whose values are linked by a many-many field class Structure(models.Model): structure_id = models.CharField(max_length=100,) drawings = models.ManyToManyField(Drawing, related_name="structures") I am trying to create a form that allows me to dynamically add structures and drawings, where each drawing must be from existing drawings. With formsets I am able to create multiple forms for 1 structure 1 drawing, but I want to be able to have multiple drawing per structure Goal is to display the inputs in the following layout How do I create a form that allows me to add multiple drawings using select -
I can't receive an email from Django Forms
I am developing a Django project. In my project, there is a form, and when I fill out the form, I can see it on the admin page. What I want to do is to receive an email notification when someone fills out the form, saying that a new form has been submitted. However, I am failing in this regard. Where is my mistake? Here is my Views.py def contact(request): if request.method == 'POST': form = ContactFormForm(request.POST) if form.is_valid(): form.save() subject = 'New Form Submitted' # message = form.cleaned_data['amessage'] message = 'There is a new form:\n\n' + \ f'Name: {form.cleaned_data["name"]}\n' + \ f'-mail adress: {form.cleaned_data["email"]}\n' + \ f'phone number: {form.cleaned_data["phone"]}\n' + \ f'call at: {form.cleaned_data["call_time"]}\n' try: email_from = EMAIL_HOST_USER recipient_list = ['xxx@mail.com'] html_message = render_to_string('contact.html', {'message': message}) msg = EmailMessage(subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() except ValueError: return HttpResponse('Invalid header found.') else: form = ContactFormForm() return render(request, 'contact.html', {'form': form}) And Here is my settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'XXX' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = 'XXX' EMAIL_USE_TLS = True -
UseEffect in React Components in Django App
I am trying to use react components within a Django app. Single components should bei integrated within an HTML. In the first step it is working: the react components are beeing rendered and everything looks fine. The problem: I have a component let's say a table, where lets say Artikel/ price data are rendered. Now due to another non-React functionality new data are uploaded from the users desktop. Of course the table should be re-rendered. But how can this be managed? I tried to solve it with useEffect and a global variable. Apart from the fact that this seems to be a anti-pattern it simply doesn't work. So the question is, how can I solve this problem? I don't have an idea. I tried any kind of research and manipulation around the usage of global variables within this context. Unfortunately without any result. -
DJango captcha Error messages getting duplicated
my captcha error messages get duplicated my template error display code: {% if form.non_field_errors %} {% for error in form.non_field_errors %} <h3 style = "color:red;text-align:center">{{ error }}</h3> {% endfor %} {% elif messages %} {% for message in messages %} <h3 class = "{% if message.tags == 'success' %} message-green {% elif message.tags == 'error' %} message-red {% endif %}" style = "text-align:center">{{message}}</h3> {% endfor %} {% endif %} and my views: def Insertvalue(request): if request.method == "POST": form = EmpInsertForm(request.POST) if form.is_valid(): form.URL = request.POST.get('URL') form.email = request.POST.get('email') form.save() messages.success(request,'Info saved. Be on the lookout for a confirmation e-mail') else: messages.error(request,'Captcha not cleared. Please try again.') return render(request,'Index.html',{"form":form}) else: form = EmpInsertForm() return render(request,'Index.html',{"form":form}) the messages.error is the one that gets duplicated. to reproduce it, I first have to get the non field error which is bascally a unique_together error, and then get the captcha error and it will be printed as many times as I got the non field error + 1. Is there any way to delete all messages in the messages array if non field error is raised? Thank you in advanced. -
Work with django user permissions in ajax/jquery
Is it possible to user django permissions inside of ajax. I have the following code in a template in django which works perfect for checking permissions. {% if perms.users.change_account %} <a class="btn btn-info btn-sm" href="/users/account_edit/"> <i class="fas fa-pencil-alt"> </i> Edit </a> {% endif %} And i have a js file with ajax and wanted to add that check for permission when adding some elements to innerhtml const sendSearchData = (dev) => { $.ajax({ type: 'POST', url: '/customers/dev_search', data: { 'csrfmiddlewaretoken': csrfDevice, 'dev': dev, 'id': cid, }, success: (res)=> { const devData = res.data if(Array.isArray(devData)){ resultsListDev.classList.remove('not-visible') resultsListDev.innerHTML = "" devData.forEach(dev=>{ resultsListDev.innerHTML += ` <tr> <td> ${dev.name} </td> <td> # Is there a way to check user permissions in django from ajax and if it has a specific permissions # then display, like how can i check this in ajax "perms.users.change_account" <a class="btn btn-info btn-sm" href="/users/account_edit/"> <i class="fas fa-pencil-alt"> </i> Edit </a> </td> </tr> ` }) } }, error: (err)=> { console.log(err) } }) } No idea on how to check user permissions from ajax in django. Tried looking through documentation and searching web, but couldn't find anything. -
What exactly PyCharm Django Test run configuration do
I have a custom test command in my Django project: class Command(test.Command): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( "--fit", action="store_true", help="Fit persistent tests instead of checking them.", ) def handle(self, *test_labels, **options): if options["fit"]: ... super(Command, self).handle(*test_labels, **options) It works when running from the console, e.g. python manage.py test --fit. However, when I'm using a PyCharm Django Tests configuration, it does not execute the handle(...) method. I can add --fit flag as an option and I can't add some random --qwerty flag. So, it means that the command is registered. While running in debug mode, I could reach the point in the add_arguments(...), but not in the handle(...) (as well as not in the django.core.management.commands.test.Command.handle(..), by the way). The only problem is that PyCharm executes this command some other way, without calling handle(...) method. So the question is - maybe someone know, what PyCharm is actually calling? -
Django upload many files & start working on them before all files are uploaded
Alright, I'm fairly new to asking questions here so bear with me. I've got a Django app that is currently in production and I'm trying to access uploaded files as each one finishes uploading rather than after all files have completed the upload process. The current solution: Upload of 10000 files starts Upload finishes Backend analyzes files asynchronously and streams them to the front in cooperation with my JS. The solution I'd like to implement: Upload of 10000 files starts Backend asynchronously analyzes the files as they come and streams them to the front end in cooperation with my JS Upload finishes I honestly just don't know where to start here and I'd appreciate any indication of the right way to do this. Additional info: Application coded in Python3.11/Django4.2/CSS(2023)/JS(ECMAScript) Files are uploaded using a JS drag & drop datastream and submitted via a Django FileField with a forms.ClearableFileInput() that accepts multiple files Application deployed on a Ubuntu 22.04 LTS server via Nginx & Gunicorn Each file analyzed can be anywhere from 17kb to 12mb By 'analyzes' I mean that calculations are run on each file to then my app produces a list of calculated values When I say that my … -
send an email to my gmail address with django in cpanel server
I have a Cpanel server which runs a Django app, and I have a form in my website that I want erverytime an anonymous user has filled the form a new email send to my Gmail address, I dont know the best practice to implement this scenario -
Attribute error : force_str(urlsafe_base64_decode(uid))
id= force_str(urlsafe_base64_decode(uid)) user=Customuser.objects.get(id=id) File "C:\Users\Abhishek\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\http.py", line 198, in urlsafe_base64_decode s = s.encode() AttributeError: 'NoneType' object has no attribute 'encode' It should not raise error during decode -
How to debug Django app with Spyder (and breakpoints)
So I created a project but if I press run, of course execute the python file I am looking at so I need to specify to run the classic manage.py but as far I can see that configuration is not by project but globally. So I can configure globally to run manage.py runserver and fix that issue easily but the second one is on how to connect for breakpoints usage without specify in the code for the pdb functions (I can find only that). Months ago I forked the original django-pdb to bump the django support https://github.com/Mte90/django-pdb-extended but the problem is that execute pdb on the whole page automatically. Online there aren't any information useful about Django for spyder, but also for Flask (to get inspiration for the configuration). I am writing here to see if someone has more hints on to achieve to use that editor to develop (and debug) in Django. -
upstream timed out error in ubuntu, using nginx, uwsgi
i'm working on a django project, and i deployed it with AWS, ubuntu, nginx and uwsgi. It work's well, but everytime i try to run a feature with big throughput, an error message below comes out and the feature doesn't work. And also i searched stack overflow, and i couldn't find someone having the same 'Unknown error' like mine. 2023/11/07 15:14:13 [error] 7487#7487: *1 upstream timed out (110: Unknown error) while reading response header from upstream, client: xx.xxx.xxx.xxx, server: _, request: "POST /file_upload/upload/ HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/docusift/uwsgi.sock", host: "xx.xxx.xxx.xx", referrer: "http://xx.xxx.xxx.xx/success_with_token/WeDkQYs84hDYcDsl/" (I hided my public ip with 'x') So i searched google, and i found that i should set the nginx, uwsgni settings. I setted up my settings like below, but it still has the same error above. [uwsgi] chdir=/home/ubuntu/docusift/blog module=blog.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/home/ubuntu/docusift/debug_uwsgi.log home=/home/ubuntu/docusift/venv virtualenv=/home/ubuntu/docusift/venv socket=/home/ubuntu/docusift/uwsgi.sock chmod-socket=666 socket-timeout=600 harakiri = 300 http-timeout = 300 server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; proxy_buffer_size 512k; proxy_buffers 16 512k; proxy_busy_buffers_size 1024k; proxy_connect_timeout 500s; proxy_send_timeout 500s; proxy_read_timeout 500s; send_timeout 500s; } location /static/ { alias /home/ubuntu/docusift/blog/staticfiles/; } http { upstream django { server unix:/home/ubuntu/docusift/uwsgi.sock; } client_max_body_size … -
django model migration problem table already exist
hello i have a legacy database which contain a users table and I want just to add to this table some field and override abstract base user of Django model auth the problem is when I am trying to migrate is says that the table users is already exist in database from django.contrib.auth.base_user import AbstractBaseUser,BaseUserManager from django.db import models import sha512_crypt import time # function that return actual timestamp def actual_epoch_time(): return int(time.time()) class UserManager(BaseUserManager): def create_user(self,email,username,password=None): user = self.model(email = normalize_email(email),username=username) user.set_password(password) user.save() return user def create_superuser(self,email,username,password=None): user = self.create_user(username=username,password=password,email=email) user.is_admin = True user.save() return user #here is the abstracted user model from xui database with additional fields class Users(AbstractBaseUser): username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255, blank=True, null=True) date_registered = models.IntegerField(default=actual_epoch_time()) last_login = models.IntegerField(blank=True, null=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) hue = models.CharField(max_length=50, blank=True, null=True) theme = models.IntegerField(blank=True, null=True) timezone = models.CharField(max_length=255, blank=True, null=True) api_key = models.CharField(max_length=64, blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'username' class Meta: managed = True db_table = 'users' def … -
Caddy: How to serve static files from Django
It's my first experience with Caddy and I'm having dificulties to configure it properly concerning static files. I'm using an Ubuntu server and I'm running Caddy and Django+Gunicorn as Docker containers. It works perfectly well except that it gives a 404 on static files such as CSS and JS files. I've collected all static files to their corresponding directories in /home/myusername/static and have the following Caddyfile: mydomain.com { encode gzip handle_path /static/* { root * "/home/myusername/static/" file_server } handle_path /media/* { root * "/home/myusername/media/" file_server } reverse_proxy django-gunicorn-container-name:8000 } What should I do to make Caddy serve static files correctly? Any suggestions will be much appreciated! Thanks! -
In Django, how to remove language prefix conditionnally after internationalization ? Media file src problem
In a django project, after a query I'm sending image srcs to a JS file that will then create popovers dynamically on my home page using these image srcs and some text data. ex : popover_photo.src = 'media/' + popover_data['photo__src'] After adding internationalization to my project, all my pages are prefixed by language code like 'en' or 'es', the problem being that my image srcs also gets prefixed by a language code automatically. Instead of having 'media/my-exemple-image.png' I will get 'en/my-exemple-image.png' and the image file won't be found. So, is there a way to remove language prefix conditionnally in django on a particular endpoint OR more specifically, is there a way to exclude my call to my media folder from having a language prefix ? Thanks in advance if any dev is willing to share a workaround about this ! My main urls.py currently looks like this (I'm still in development, but I'm going to use AWS S3 in a bit to stock my images, might the same problem occur?): urlpatterns = [ path('admin/', admin.site.urls), path('__debug__/', include('debug_toolbar.urls')), ] urlpatterns += urlpatterns + i18n_patterns( path('rosetta/', include('rosetta.urls')), path('', include('core.example_app.urls', namespace='example_app')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
The tests are failing in GitHub Actions
I'm writing the backend on Django in a Docker container. I've created models and tests for them, and here's the issue: the tests pass locally and everything works fine. However, when I push the code to GitHub, I encounter this error during test execution in GitHub Actions: `django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Error: Process completed with exit code 1. Please, can you help me with this? Docker-compose.yml version: '3.11' services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: Dockerfile FROM python:3.11.5-alpine LABEL maintainer="https://github.com/Arvitheslayer" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip …