Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize snake_case model fields to camelCase in django rest framework
I'm adding REST API endpoints to my existing Django application. I'm using DRF ModelSerializer. My model classes follow the pep8 naming convention and use snake_case for field names, but I need the JSON response to be in camelCase. How can I achieve that in a cross-cutting way without defining proxy fields on each of my serializers? -
How to solve Django error 'django.db.utils.IntegrityError: NOT NULL constraint failed: myapi_article.author_id’
I am attempting to build a dummy news site to learn django. I am running into the stated error when performing a POST request to create a new article which is linked to a signed in user via the author ForeignKey. Users are handled using JWT on the front end. I have been stuck on this for a few days and am out of places to look for answers. Here are the serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password', 'email'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ArticleSerializer(serializers.ModelSerializer): author= UserSerializer(read_only=True) class Meta: model = Article fields = '__all__' #read_only_fields = ['author'] Here is the relevant view: class ArticleCreateView(generics.ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(author=self.request.user) and here is the relevant model: class Article(models.Model): headline = models.CharField(max_length=200) subtitle = models.CharField(max_length=300) section = models.CharField(max_length=200, blank=True, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='articles') body = models.TextField() #pub_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) endorsements = models.IntegerField(default=0, blank=True, null=True) def __str__(self): return self.headline I am aware that I could set the author field to accept null/blank values and silence the error, but this would not really solve the … -
500 Internal Server Error Exception inside application. Daphne
ValueError: No application configured for scope type 'http' in my django terminal message It's my first time using Stack Overflow, so it's hard. Please understand if I'm not good at asking questions import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hyean.settings') application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) this is my asgi.py code help me! thank you guys settings.py ASGI_APPLICATION = 'hyean.asgi.application' -
ajax not passing data to view in Django
I am trying to send ajax request but request QueryDict is empty index.html var coin = Number(localStorage.getItem("coin")) if (coin!=0) { debugger $.ajax({ url:"/", method:"POST", headers:{"X-CSRFToken":$("input[name=csrfmiddlewaretoken]").val()}, data:{"coin":coin}, contentType:"application/json", success:function(data){ console.log(data) localStorage.setItem("coin",0) }, error:function(errMsg){ console.log(errMsg) localStorage.setItem("coin",0) } }) } views.py elif request.method == "POST": print(request.POST) response = JsonResponse({"a":"b"},status=200) return response cmd <QueryDict: {}> [09/Jun/2024 09:36:49] "POST / HTTP/1.1" 200 10 web console web console image output i expect in cmd <QueryDict: {"coin":anynumber }> [09/Jun/2024 09:36:49] "POST / HTTP/1.1" 200 10 -
Django SMTPServerDisconnected at /reset_password/ Connection unexpectedly closed
So I am trying to send a password reset link to users but I keep getting this error. My views.py: def password_reset_request_view(request): if request.method == 'POST': email = request.POST.get('email') if email: try: user = CustomUser.objects.get(email=email) subject = "Password Reset Requested" email_template_name = "users/password_reset_email.html" c = { "email": user.email, "domain": request.get_host(), "site_name": "Your Site", "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, "token": default_token_generator.make_token(user), "protocol": 'http', } email_content = render_to_string(email_template_name, c) logger.debug(f"Sending email to {user.email}") logger.debug(f"Email content: {email_content}") # Create an SMTP connection with debug level set to 1 connection = get_connection() connection.open() connection.connection.set_debuglevel(1) send_mail( subject, email_content, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False, connection=connection ) messages.success(request, 'A message with reset password instructions has been sent to your inbox.') logger.debug("Email sent successfully") return redirect('password_reset_done') except CustomUser.DoesNotExist: messages.error(request, 'No account found with this email address.') logger.error("No account found with this email address") return redirect('reset_password') return render(request, 'users/password_reset.html') My settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mail.yahoo.com' # Your email service SMTP server EMAIL_PORT = 587 # The port your SMTP server uses (e.g., 587 for TLS) EMAIL_USE_TLS = True # Use TLS for security EMAIL_HOST_USER = 'abrarshahriar360@yahoo.com' # Your email address EMAIL_HOST_PASSWORD = 'password' # Your email password DEFAULT_FROM_EMAIL = 'abrarshahriar360@yahoo.com' # Default from email address I feel like my code … -
How can I build the Backend for a reminding feature like in Google Calendar using django and python?
I need to implement a feature that has a recurring nature to it. A user will be able to set a reminder and that reminder will have a frequency to it. The types of frequency are as follows: Daily Weekly Biweekly Monthly Bimonthly Quarterly Half Yearly Yearly Biyearly And to top it off I also need to allow the user to add a "remind me {x} hours before {the scheduled reminder}" Please HELP! Can somebody explain to me the technologies I'll need to use to build a feature like this? To be more precise—to build the backend for it. I did some research and found out about Celery & Redis as the way to go besides a Cron job. And then upon finding out about Celery-Beat I gave up. Why? Because it's all so very confusing and complex. I'm not sure if this is the right way, or not. It seems to me like this could be made inefficiently very easily, if done by brute-force, or very complex, if done efficiently. -
Intermittent Process Stoppage with Requests Library in Django App on Google Compute Engine When Using Gemini API
I am developing a web application with Django. The environment is n2-standard-2(debian) on Google Compute Engine. I am using the requests library to make a request to use gemini-1.5-flash using the API as shown in the following [script]. Normally, [1] is followed by a DEBUG log for [2], but once in 4 times, the process stops working with [1] (no [2] or later is generated and the process stops working as is). It works fine in the local environment (windows), but it always occurs in the GCE environment. Please tell me why does it happen and how to collect it. [1]DEBUG: urllib3.connectionpool:starting new HTTPS connection (1): generativelanguage.googleapis.com: 443 [2]DEBUG: urllib3.connectionpool:https://generativelanguage.googleapis.com:443 “POST /v1/models/gemini-1.5-flash:generateContent?key= hogehoge HTTP/1.1” 200 None [Script] response = session.post(url, headers=headers, json=data, timeout=20) I tried to force a timeout using signal.signal(signal.SIGALRM, timeout_handler) and signal.alarm(20), but no luck -
authenticate() returns none in django
In django i have created a custom user and custom user manager as below: this is my models.py codes: class CustomUserManager(BaseUserManager): def create_user(self, phone_number, password=None): if not phone_number: raise ValueError('وارد کردن تلفن همراه ضروری میباشد.') user = self.model(phone_number=phone_number) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password): user = self.model(phone_number=phone_number) user.set_password(password) user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = None name = models.CharField(max_length=30, blank=True, null=True) phone_regex = RegexValidator(regex=r'^09\d{9}$', message="شماره تلفن را به صورت ۰۹********* وارد کنید.") phone_number = models.CharField(max_length=11, validators=[phone_regex], unique=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' objects = CustomUserManager() def __str__(self): return self.phone_number this is my forms.py codes: class UserSignupForm(forms.Form): def __init__(self, *args, **kwargs): super(UserSignupForm, self).__init__(*args, **kwargs) self.fields['phone_number'].label = "شماره تلفن" self.fields['phone_number'].widget.attrs['class'] = 'form-control input-bg-white l-field' self.fields['password'].label = "رمز عبور" self.fields['password'].widget.attrs['class'] = 'form-control input-bg-white l-field' self.fields['password'].widget.attrs['id'] = 'login-signup-pass' def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if CustomUser.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError("این شماره تلفن قبلا در سایت ثبت شده است.", code="already-exist") return phone_number phone_number = forms.CharField( widget=forms.TextInput(attrs={'placeholder': "09123456789"}), validators=[RegexValidator(r'^09\d{9}$', message="شماره تلفن وارد شده معتبر نمیباشد.")] ) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ['phone_number', 'password'] and this is my views.py codes: if request.method == 'POST': user_signup_form = UserSignupForm(request.POST) repairman_signup_form = RepairmanSignupForm(request.POST) if user_signup_form.is_valid() … -
How to handle permissions of media files uploaded in django?
Need urgent help Hi guys, need a help about a project. How can I handle media files securely in django and Django rest framework? Basically the files should be private. For example, suppose this is a digital product website, where the buyer will only get access to the file if he/she purchases the digital product. Otherwise, the product file should be private. I can handle the permissions of drf and django views. But usually the media files are not private, the media files can be access via url easily. If one buyer purchases and share the file link with others everyone can download even without creating an account. So how can I handle this? Also how can I handle video files, that needs to be streamed to the frontend. Thanks -
Is it possible to implement different colours for the various components, such as minimum, maximum, quartiles and median in box and whisker plot?
I am searching for a library or html and javascript code to implement box and whisker plot and each component such as minimum, maximum, quartiles and median should be represented in different colours. Is it possible to implement such box and whisker plot? -
How to start celery beat on azure app service
I want my django app run celery beat automatically without start. I have deployed my django api on azure app service. How can i start celery beat on startup and make it always run without manual start. I Have setup celery with azure cache redis. -
elastic search index is not creating
I tried to create search index in elastic search using document and manually both gives error: curl -X PUT "localhost:9200/elastic_book" -H 'Content-Type: application/json' -d' { "mappings": { "properties": { "title": { "type": "text" }, "description": { "type": "text" }, "author": { "type": "text" } } } } ' {"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]"}],"type":"mapper_parsing_exception","reason":"Failed to parse mapping [properties]: Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]","caused_by":{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]"}},"status":400} PUBLISHER_INDEX = Index('elastic_book') PUBLISHER_INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @PUBLISHER_INDEX.doc_type class BookDocument(Document): title = fields.TextField() description = fields.TextField() author = fields.TextField() class Django: model = Book when i run the python manage.py search_index --rebuild command it gives : raise HTTP_EXCEPTIONS.get(status_code, TransportError)( elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [author : {type=text}] [description : {type=text}] [title : {type=text}]') -
Celery: attach custom logger to default celery handler (logfile)
I would like to have a logger that can be used both in django and in celery. When used by django it should print to console, while when used from a celery task, I would like it to output using the default celery handler (in my case, it dumps to a file specified by the --logfile cmd line argument). This is especially useful for helper functions that are used by both the django server and celery tasks. This is what I have in my settings.py file: LOGLEVEL = os.environ.get("LOGLEVEL", "info").upper() LOGGING = { "version": 1, # the dictConfig format version "disable_existing_loggers": False, # retain the default loggers "handlers": { # console logs to stderr "console": { "class": "logging.StreamHandler", "formatter": "verbose", }, "django.server": DEFAULT_LOGGING["handlers"]["django.server"], }, "formatters": { "verbose": { "format": "[{asctime}]|{levelname}| {message}", "style": "{", }, "django.server": { # "()": "django.utils.log.ServerFormatter", "format": "[{asctime}]|{levelname}| {message}", "style": "{", }, }, "loggers": { # default for all undefined Python modules "": { "level": "WARNING", "handlers": ["console"], }, # Our application code "app": { "level": LOGLEVEL, "handlers": ["console"], # Avoid double logging because of root logger "propagate": False, }, # Default runserver request logging "django.server": DEFAULT_LOGGING["loggers"]["django.server"], "django.channels.server": DEFAULT_LOGGING["loggers"]["django.server"], }, } In my "app" logger, I have … -
how to Implement non-blocking, sequential AI moves in a multiplayer chess game in django channels?
I'm developing a website to play a special with kind of chess with React and Django. It pretty much requires two games to be played at the same time. The website allows to add AI players, so the common scenario is to have board 1 (human vs AI) and board 2 (AI vs AI). I want the computer players to behave in a manner that they play a move, wait a second, then let another one play, not blocking other games. The problem is that the following code makes the entire AI vs AI game play in a blink of an eye and makes it impossible to send and receive any event (even the game.start event does not get sent). This is my code that triggers the computers playing against each other: for game in started_games: await self.channel_layer.group_send( self.room_group_name, {'type': 'game.start'}) if self.is_ai_turn_in_game(game): if game.gamemode == GameMode.CLASSICAL.value: board = chess.Board(fen=game.fen) else: board = chess.variant.CrazyhouseBoard(fen=game.fen) print(self.is_ai_turn_in_game(game)) while self.is_ai_turn_in_game(game): await self.handle_ai_turn(game, board) await self.send_move_to_clients(game) self.send_move_to_clients processes some data, then calls await self.channel_layer.group_send( self.room_group_name, {'type': 'game.move', 'message': response_data} ) which executes the following code: async def game_move(self, event): move = event['message'] await self.send(json.dumps(move)) await asyncio.sleep(1) I am wondering if I should use a … -
Is there an option to use nginx instead of traefik?
The "Select a front-end web server/proxy to use" option seems to be gone. I'm using cookiecutter-django's docker compose setup. I'd rather use nginx (a more familiar technology without the excessive abstractions of traefik). -
comments are being saved in database to related post but not accessed in template even variable is correct
comments are being saved in database to related post but not accessed in template even variable is correct on debuging it shows the comment to realted post but not fetching it to the template only commet.count function showing one comment here is template {{ comment.count }} {% for comment in comment5 %} {{comment.user}} {{comment.datetime}} {{comment.content}} {% endfor %} def blogpost1(request, id): post = get_object_or_404(Post, id=id) comment5=Comment.objects.filter(blog=post) print(f"Post: {post}") print(f"Comments: {comment5}") # Debugging statement for comment in comment5: print(comment.id, comment.user, comment.content) print(comment5) if request.method=='POST': user = request.user content=request.POST.get('content') comment=Comment(user=user,content=content,blog=post) comment.save() return render(request,'singlpost.html',{'post':post,'comment':comment5}) -
How to host two django apps on windows using apache and mod_wsgi?
I know how to run 1 django application on windows server using mod_wsgi & apache. Now I want to run more than one django application on the same server. I have the following configurations httpd.conf at the end of the file I added LoadFile "C:/Python312/python312.dll" LoadModule wsgi_module "C:/Python312/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" #WSGIPythonHome "C:/Python312" windows_wsgi.py for application app1 # Activate this path from virtual env activate_this = "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Scripts/activate_this.py" exec(open(activate_this).read(),dict(__file__=activate_this)) import os # import site import sys from decouple import config # Add the site-packages of the selected virtual env to work with # site.addsitedir = "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages" sys.path.append("C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages") sys.path.insert(0, "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages") # Add teh app directory to the PYTHON PATH sys.path.append("C:/Apache24/htdocs/app1") sys.path.append("C:/Apache24/htdocs/app1/app1") os.environ['DJANGO_SETTINGS_MODULE'] = config('DJANGO_SETTINGS_MODULE') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() windows_wsgi.py for app2 # Activate this path from virtual env activate_this = "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Scripts/activate_this.py" exec(open(activate_this).read(),dict(__file__=activate_this)) import os # import site import sys from decouple import config # Add the site-packages of the selected virtual env to work with # site.addsitedir = "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages" sys.path.append("C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages") sys.path.insert(0, "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages") # Add the app directory to the PYTHON PATH sys.path.append("C:/Apache24/htdocs/app2") sys.path.append("C:/Apache24/htdocs/app2/app2") os.environ['DJANGO_SETTINGS_MODULE'] = config('DJANGO_SETTINGS_MODULE') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd-vhosts.conf settings <VirtualHost *:92> ServerName app1.localhost WSGIPassAuthorization On ErrorLog "logs/app1.error.log" CustomLog "logs/app1.access.log" combined WSGIScriptAlias / "C:\Apache24\htdocs\app1\app1\wsgi_windows.py" application-group=%{app1} <Directory "C:\Apache24\htdocs\app1\app1"> … -
What is so dofficult for Django to work out about display media images on my template?
Right, what is so difficult for Django to work out in pertinence to displaying an image on a template when DEBUG is set to False? Why is it, when I do literally everything correctly, does it just outright refused to display the bloody image on the page? Why is it, when I have correctly set up my MEDIA_URL and my MEDIA_ROOT in my settings.py, does it still refuse to load the page? Why is it that despite correctly setting up my root urls.py page in the following fasion, does Django refuse to the display the image in the webpage: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Why is is that, despite correctly setting up the upload_to directly in my models.py file, run the makemigrations as well as the migrate command, does Django....you get the idea. Why is that that despite installing whitenoise, and running the py manage.py collectstatic command doesnt Django...oh yes, sorry, we've done this before. Why is is that when I go to "inspect source" in my web browser does it return the correct image directory, yet when I click on the image URL directory from the inspect source page, does it return my beautifully-crafted custom 404 page? I know, shocker … -
Integrity Error - UNIQUE constraint failed. How do i deal with it? Django
I am new to the DRF framework, and am building a small project. I want to create a User instance (the built-in one) and while doing so also make a Seller instance linked to it during a user signup. Whenever i try to do this, Django throws an Integrity Error : UNIQUE constraint failed: seller_seller.user_id. Can you all help me understand this issue and to fix it? Please ask if more information is required. models.py class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) seller_company_name = models.CharField(max_length=200) seller_contact = models.CharField(max_length=14, null=True) seller_email = models.EmailField(max_length=200, null=True) def __str__(self): return f"{self.id} --> {self.user.username}" serializers.py class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) contact = serializers.CharField(max_length=15, required=True) cname = serializers.CharField(max_length=200, required=True) class Meta: model = User fields = ['id', 'username', 'email', 'password', 'contact', 'cname'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): try: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], ) except IntegrityError: raise serializers.ValidationError("Username or email already exists.") try: seller = Seller.objects.create( user=user, seller_contact=validated_data['contact'], seller_company_name=validated_data['cname'], seller_email=validated_data['email'], ) except IntegrityError as e: user.delete() # Rollback user creation if seller creation fails raise serializers.ValidationError("Failed to create seller.") return user signup view @api_view(['POST']) @permission_classes([AllowAny]) def signup_view(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) I have … -
Is it possible localhost html file with python http module like django
So i was trying to make localhost with http.server i used some help from docs but i got an error i tried to fix still unable to fix it here is the code: from http.server import BaseHTTPRequestHandler, HTTPServer loop = True def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler): server_address = ('result.html', 5050) httpd = server_class(server_address, handler_class) httpd.serve_forever() if loop == True: httpd.server_close() while loop: run() ex = input("To close the server write 'exit' /n <<< ") if ex.find(f'exit'): loop = False Error: Traceback (most recent call last): File "E:\Python\localhost\main.py", line 36, in <module> run() File "E:\Python\localhost\main.py", line 5, in run httpd = server_class(server_address, handler_class) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\socketserver.py", line 457, in __init__ self.server_bind() File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\http\server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\socketserver.py", line 473, in server_bind self.socket.bind(self.server_address) socket.gaierror: [Errno 11001] getaddrinfo failed Process finished with exit code 1 -
django rest framework LimitOffsetPagination when modifying results
I'm using django rest frame work and want LimitOffsetPagination https://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination to work on the json output of my view class MyList(generics.ListAPIView) which has thousands of records to potentially page through. I can't figure out how to get it working as desired without fetching all the potential records vs only the slice needed for a given page. The problem is introduced by the fact that I have to modify the records before returning from the view, I can't just return a queryset, I return my customized list of records. If I merely do some queryset manipulation and return a queryset, everything works great. SQL to the DB uses LIMIT and OFFSET so it's fast, a page of records is fetched, and json is paged as expected. I need to modify the results of the queryset however and as soon as I evaluate it mylist = list(queryset) SQL does NOT use LIMIT and OFFSET it fetches all the records. If I use slice notation on the queryset queryset[offset:offset+limit] to force it to only get what I want, then modify those results that works up to a point(SQL uses LIMIT and OFFSET etc). The problem is say the slice was 100 records, the … -
TypeError: Group name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not
import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import User, Connection, Message import logging from .serializers import ( MessageSerializer ) from app.serializers import ( UserSerializer, ) logger = logging.getLogger(name) class ChatConsumer(WebsocketConsumer): def connect(self): user = self.scope['user'] self.accept() if not user.is_authenticated: return self.username = user.username # Join user to group async_to_sync(self.channel_layer.group_add)( self.username, self.channel_name ) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.username, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) data_source = data.get('source') self.send(text_data=json.dumps({"message": data.get('message')})) if data_source == 'message.send': user = self.scope['user'] connectionId = data.get('connectionId') message_text = data.get('message') receiver = User.objects.get(username=data.get('user_receiver')) try: connection = Connection.objects.get(id=connectionId) except Connection.DoesNotExist: connection = Connection.objects.create( sender=user, receiver=receiver, ) return message = Message.objects.create( connection=connection, user=user, text=message_text ) # Get recipient friend recipient = connection.sender if connection.sender == user: recipient = connection.receiver messages = Message.objects.filter( connection=connection ).order_by('-created') serialized_messages = MessageSerializer( messages, context={ 'user': user }, many=True ) # Send new message back to sender serialized_message = MessageSerializer( message, context={ 'user': user } ) serialized_friend = UserSerializer(recipient) data = { 'message': serialized_message.data, 'messages': serialized_messages.data, 'friend': serialized_friend.data } self.send_group(user.username, 'message.send', data) # Send new message to receiver serialized_message = MessageSerializer( message, context={ 'user': recipient } ) serialized_friend = UserSerializer(user) data = { 'message': serialized_message.data, 'messages': serialized_messages.data, 'friend': serialized_friend.data } … -
Organizing Django Project: Separating App into Multiple Servers with Shared Database and User Model
In our project, we plan to split one Django app from the monolith into a separate server, while using a single database for both. I don't understand how to correctly utilize the user model, which will be shared between the two servers. Should migrations, both existing and future ones, remain in one repository or should they be split between the two? class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(_("Email address"), unique=True) email_verified = models.BooleanField(default=False) first_name = models.CharField(_("first name"), max_length=100, blank=True, null=True) last_name = models.CharField(_("last name"), max_length=100, blank=True, null=True Explored various architectural options for splitting a Django app into two servers with a shared database. Reviewed Django documentation regarding the use of a shared user model. Expecting to find an optimal way to utilize the user model in this scenario and ensure migration synchronization for both servers -
I want to find a method to avoid complexity and coupling in django models + rest api
I created a model for an API. After that, I planned to add more APIs from different platforms. however, all of the APIs were for the same purpose but the data they required and their methods of accepting the data differ. For example. (it's just an example to explain, not the actual case but 90% similar) I create a model with attributes (name, email, password), but the second API is using (firstname, lastname, email, password). Maybe the third API will ask for (Surname, country, oassword) etc. Then I wanted to create a view to perform CRUD operation. But to know which crud should be done for which API, I created a class with the name CRUD handler in which the class will specify which one to use. I also created another class with the name 'BOT' which had a unique secret key to identify which user wants to use which API. So that every time the credentials are not meant to be sent for safety. Almost all of them use/support the REST framework This is the flow that I want: some_other_WEbsite -> (sends data with secret key) -> djangoview -> BOT ->(uses secret key) to identify the USER, the API … -
I want to show users who selected a particular role, on a dropdown in another form,,
PERSONAL DATA user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) image = models.FileField(_('Profile Image'),upload_to='profiles',default='default.png',blank=True,null=True,help_text='upload image size less than 2.0MB')#work on path username-date/image firstname = models.CharField(_('Firstname'),max_length=125,null=False,blank=False) lastname = models.CharField(_('Lastname'),max_length=125,null=False,blank=False) # linemanager = models.CharField(_('Line manager'),max_length=125,null=False,blank=False,default='mr.....') # birthday = models.DateField(_('Birthday'),blank=False,null=False) phone = models.CharField(_('Phone number'),max_length=12,null=False,blank=False,help_text='enter phone number') department = models.ForeignKey(Department,verbose_name =_('Department'),on_delete=models.SET_NULL,null=True,default=None) role = models.ForeignKey(Role,verbose_name =_('Role'),on_delete=models.SET_NULL,null=True,default=None) this is the employee models.py where i add a staff and select a particular role def dashboard_employees_create(request): if not (request.user.is_authenticated and request.user.is_superuser and request.user.is_staff): return redirect('/') if request.method == 'POST': form = EmployeeCreateForm(request.POST,request.FILES) if form.is_valid(): instance = form.save(commit = False) user = request.POST.get('user') assigned_user = User.objects.get(id = user) instance.user = assigned_user instance.title = request.POST.get('title') instance.image = request.FILES.get('image') instance.firstname = request.POST.get('firstname') instance.lastname = request.POST.get('lastname') instance.phone = request.POST.get('phone') role = request.POST.get('role') role_instance = Role.objects.get(id = role) instance.role = role_instance instance.startdate = request.POST.get('startdate') instance.employeetype = request.POST.get('employeetype') instance.employeeid = request.POST.get('employeeid') # instance.dateissued = request.POST.get('dateissued') instance.save() This is the views class LeaveCreationForm(forms.ModelForm): reason = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 4, 'cols': 40})) class Meta: model = Leave exclude = ['user','defaultdays','hrcomments','status','is_approved','updated','created'] this is what my leave creation form looks like