Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'
I've been trying to merge Vue and Django for a long time, but my efforts are even. Here is the error that I can't solve for a long time: ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'publicPath'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } Do you have any options for solving this problem? Maybe there is another way to combine them. Vue.config.js var BundleTracker = require('webpack-bundle-tracker') var WriteFilePlugin = require('write-file-webpack-plugin') module.exports = { outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'), publicPath: '/', devServer: { publicPath: "http://localhost:8080/", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method", "Access-Control-Allow-Credentials": "true" } }, chainWebpack: config => { config.optimization.splitChunks({ cacheGroups: { vendors: { name: 'chunk-vendors', test: /[\\\/]node_modules[\\\\/]/, priority: -10, chunks: 'initial' }, common: { name: 'chunk-common', minChunks: 2, priority: -20, chunks: 'initial', reuseExistingChunk: true } } }) }, configureWebpack: { output: { filename: 'js/[name].js', chunkFilename: 'js/[name].js' }, plugins: … -
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) while sending notification using firebase in django
JSONDecodeError at /send-notif/ Expecting value: line 1 column 1 (char 0) code `def send_notification(registration_ids , message_title , message_desc): fcm_api = "" url = "https://fcm.googleapis.com/fcm/send" headers = { "Content-Type":"application/json", "Authorization": 'key='+fcm_api } payload = { "registration_ids" :['e1aLmMZPeegz36PP3KUw0t:APA91bGjoJBwraENbW9PHsE5IUVIh_lLhnPI99qqr_VewvRFLjbJbu_vcSfT0dk4Tu4CGbcvUfR-x8INAkqovEDuJB4OdQma2NrEPsGufjtrsizYskD_ANCpKjT5wltIAfzJkbjY0YAV'], "priority" : "high", "notification" : { "body" : "message desc", "title" : "message_title", "image" : "https://i.ytimg.com/vi/m5WUPHRgdOA/hqdefault.jpg?sqp=-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLDwz-yjKEdwxvKjwMANGk5BedCOXQ", "icon": "https://yt3.ggpht.com/ytc/AKedOLSMvoy4DeAVkMSAuiuaBdIGKC7a5Ib75bKzKO3jHg=s900-c-k-c0x00ffffff-no-rj", } } result = requests.post(url, data=json.dumps(payload), headers=headers ) print(result.json())` not able to send notifications to my user -
barcode reading with mobile camera in python django
I am trying to access mobile camera for bar code scanner for a project in python django and connect to mssql server. In which way I can use this. Anybody can guide me. I have tried Quagga and jquery. But it is not working. help in python django -
Django with False sending error message through email 10 times on a single error
Here is the code: server_error function in core url. def server_error(request): """ Custom error handler for reporting errors to the superuser via email and sending the detailed error response. """ if request.method in ('GET', 'POST'): subject = f"Error on {request.get_host()}" user = request.user if request.user.is_authenticated else None # Include username and user ID in the subject if the user exists if user: subject += f" - User: {user.username} (ID: {user.id})" # Generate the detailed error response response = technical_500_response(request, *sys.exc_info(), status_code=500) # Capture the HTML content html_content = response.content.decode('utf-8') # Send the email with the error details email = EmailMessage(subject, body=html_content, from_email='noreply@questionsbank.net', to=[settings.DEBUG_EMAIL]) # Set the content type to HTML email.content_subtype = 'html' # Send the email email.send() error_email_sent = True # Raise an exception to trigger the error handling (optional) raise Exception("Server Error") handler500 = 'project.urls.server_error' fake_error_view which is set to http://127.0.0.1:8000/fake-error/ def fake_error_view(request): raise ValueError("This is a fake error!") If debug is turned True, it shows one error page on the browser; when debug mode it turned False, I receive the same error through email, where the same email is sent 10 times instead of once. Can anyone help me understand the issue? -
django - Can't install the add-on django-bootstrap-form
I'm using the django-bootstrap-form addon in my few projects. I've never had a problem with the installation. I just tried and successfully installed it in a new project in Windows. However, I'm having trouble installing this on Linux. Below error: root@debian:/var/www/redprogram# python3 -m pip install django-bootstrap-form Collecting django-bootstrap-form Using cached django-bootstrap-form-3.4.tar.gz (4.4 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 14, in <module> File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/__init__.py", line 17, in <module> from setuptools.dist import Distribution File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/dist.py", line 42, in <module> from . import _entry_points File "/var/www/redprogram/venv/lib/python3.10/site-packages/setuptools/_entry_points.py", line 43, in <module> def validate(eps: metadata.EntryPoints): AttributeError: module 'importlib.metadata' has no attribute 'EntryPoints' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. I will add that I use django-bootstrap-form in a few other projects on the same computer but they were installed some … -
Problems with Python installation and Pycharm virtual environments
I've been using PyCharm for a while now, when I first started using it python 3.7 was the latest release so I used that, everything worked fine (~8 different projects). However, the latest version of Django requires python 3.8 or later so I finally updated and installed 3.11. I'm having some problems setting up my Pycharm projects with python 3.11 (my system can't import Django even though it's installed, I think it stems from the project not being in a venv but I've tried to add it into one).I've installed python 3.11 in the default location, the same place python 3.7 was installed but when I choose a python interpreter (screenshot below) many of them are invalid. I also notice that many of my other projects (FaceComparison as an example) are using a python 3.7 that itself is within a virtual environment, within the Scripts folder by the looks of it. Should I have installed python 3.11 in a virtual environment? Whenever I try and set up a new project and use a python 3.11 interpreter, a) it's got (DjangoTesting) in it - not sure why? and it also isn't in a virtual environment. I've read many questions about Pycharm, … -
Django Python: How to code a Social-Media-Explore Page?
Hey I am working on a Social Media Website, I have almost everything done, but I need a Explore Page with Posts based on their interests, everybodys Explore Page should look different. Where should I start? I have looked up the Internet for Projects, but i haven't found anything. I don't know where to start. Feel free to post links of Websites that could help me, thank you. -
Am trying to exclude from the GET request the parameters that does not contain values
I have this code in the search.html <h1>Property Search</h1> <hr> <form method="GET" action="/search/results/?{{ query_params }}" class="form-inline" style="display: flex; justify-content: center; align-items: center; "> <div class="form-group mx-sm-3 mb-2"> <label for="inputSaleRent" class="mr-2" style="margin-right: 10px; font-weight: bold;">Sale/Rent:</label> <select id="inputSaleRent" name="sale_rent" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="sale">For Sale</option> <option value="rent">For Rent</option> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputDistrict" class="mr-2" style="margin-right: 10px; font-weight: bold;">District:</label> <select id="inputDistrict" name="district" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="District 1">District 1</option> <option value="District 2">District 2</option> <!-- Add more district options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputMunicipality" class="mr-2" style="margin-right: 10px; font-weight: bold;">Municipality/Community:</label> <select id="inputMunicipality" name="municipality" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="Municipality 1">Municipality 1</option> <option value="Municipality 2">Municipality 2</option> <!-- Add more municipality options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputParish" class="mr-2" style="margin-right: 10px; font-weight: bold;">Parish:</label> <select id="inputParish" name="parish" class="form-control" style="width: 150px; margin-right: 10px;"> <option value="">Choose...</option> <option value="Parish 1">Parish 1</option> <option value="Parish 2">Parish 2</option> <!-- Add more parish options --> </select> </div> <div class="form-group mx-sm-3 mb-2" style="display: flex; align-items: center;"> <label for="inputPropertyType" class="mr-2" style="margin-right: 10px; font-weight: bold;">Property Type:</label> <select id="inputPropertyType" name="property_type" class="form-control" style="width: 150px; margin-right: 10px;"> <option … -
NoReverseMatch at /AddBid/1 Reverse for'addComment' withkeyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['addComment/(?P<id>[0-9]+)\\Z']
When I click on bid I receive the NoReverseMatch error. In my views, I pass different times and successfully the id as input to the view. When it comes to the AddComment function, the id seems not passed. Views: def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) IsWatchlist = request.user in listing.watchlist.all() allComments = Comment.objects.filter(listing=listing) return render(request, "auctions/listing.html", { "listing": listing, "ItemisinIsWatchlist": IsWatchlist, "allComments":allComments }) @login_required def addwatchlist(request, id): listingData = Listing.objects.get(pk= id) current_user= request.user listingData.watchlist.add(current_user) return HttpResponseRedirect(reverse("listing", args=(id, ))) @login_required def removewatchlist(request, id): listingData = Listing.objects.get(pk= id) current_user= request.user listingData.watchlist.remove(current_user) return HttpResponseRedirect(reverse("listing", args=(id, ))) def addComment(request, id): currentUser = request.user listingData = Listing.objects.get(pk=id) message = request.POST["newComment"] newComment = Comment( author = currentUser, listing = listingData, message = message ) newComment.save() return HttpResponseRedirect(reverse("listing", args=(id, ))) @login_required def AddBid(request, id): listingBid = Listing.objects.get(pk=id) newBid = request.POST["newBid"] if int(newBid) > listingBid.bid.bid: updateBid= Bid(bid=int(newBid), user=request.user) updateBid.save() listingBid.bid.bid = int(newBid) listingBid.save() return render(request, "auctions/listing.html") else: return render(request, "auctions/listing.html") HTML: {% if user.is_authenticated %} <p> {% if ItemisinIsWatchlist %} <form action="{% url 'removewatchlist' id=listing.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger">Remove from watchlist</button> </form> {% else %} {% if listing.id %} <form action="{% url 'addwatchlist' id=listing.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-success">Add … -
How to add additional user data upon first social sign in with django-allauth?
In Django REST framework, when a user signs in via a social account, say Google, I post to 127.0.0.1/accounts/google with an 'access_token' from the frontend client. 'django-allauth' then pulls data like first name, last name, email from Google, and even creates a username. However, I want to enforce two additional required fields dob (date of birth) and gender, and allow for a custom username when the user first signs in via a social account. How can I POST to 127.0.0.1/accounts/google with additional data? Or are there other ways to do so? I tried changing allauth.socialaccounts.form.SignUpForm, but it doesn't seem to work with Django REST framework. -
Error: 'EventsRaw' has no ForeignKey to 'UserEvents' - Reverse-Related GenericForeignKey Inline Form in Django Admin
I'm encountering an error while attempting to add a reverse-related GenericForeignKey inline form to a model in Django admin. The specific error message states: "'EventsRaw' has no ForeignKey to 'UserEvents'." To provide better context and clarity, I have created simplified example files. By reviewing these files, you will have a clearer understanding of my intention: https://share.getcloudapp.com/v1uWyox0 Here's what I need assistance with: Displaying UserEvents in the Django admin dashboard. When navigating to the UserEvents page in the admin dashboard, I would like to see a list of all EventsRaw objects that are reverse-related. Thank you in advance for your help! -
Django: Format dates according to settings.LANGUAGE_CODE in code (e.g. messages)
In my Django 4.2 app's settings.py I have # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = "de-CH" TIME_ZONE = "CET" USE_I18N = True USE_TZ = True which works in templates, e.g. {{ training.date | date:"l, j. M." }} is displayed as Sonntag, 11. Jun.. However, if I use strftime in the code, e.g. self.success_message = ( f"Eingeschrieben für <b>{self.date.strftime('%A')}</b>, " f"den {self.date.strftime('%d. %B %Y')}.".replace(" 0", " ") ) I end up with Eingeschrieben für Thursday, den 15. June 2023.. How do I get get date strings according to settings.LANGUAGE_CODE from code? -
Django Async (uvicorn) is very slow
I have a boilerplate app and was playing around with Django Async(planning to add some GraphQL + subscriptions) and made a benchmark that shocked me. Gunicorn with async worker uvicorn is much more slower than gthread. Async Code: async def my_async_view(request): return JsonResponse( {"async accounts": "Test"}, status=200, ) Gunicorn Async command: gunicorn --worker-class uvicorn.workers.UvicornWorker banking_api.asgi --workers=8 --threads=2 Sync Code def my_sync_view(request): return JsonResponse( {"sync accounts": "Test"}, status=200, ) Gunicorn Sync command: gunicorn banking_api.wsgi --workers=8 --threads=2 Benchmark results: Async: Running 30s test @ http://localhost:8000/test/ 12 threads and 50 connections Thread Stats Avg Stdev Max +/- Stdev Latency 57.72ms 75.82ms 1.08s 97.25% Req/Sec 81.90 44.42 232.00 81.61% 29007 requests in 30.05s, 8.08MB read Requests/sec: 965.41 Sync: Running 30s test @ http://localhost:8000/test/ 12 threads and 50 connections Thread Stats Avg Stdev Max +/- Stdev Latency 24.26ms 44.37ms 865.76ms 92.37% Req/Sec 281.56 146.56 0.89k 66.32% 100051 requests in 30.08s, 30.25MB read Requests/sec: 3326.37 What is happening? Why the difference of Requests/sec of 3326.37 (sync) vs 965.41 (async) ? Am I doing something wrong here? Thanks -
regarding slashes using in urls pattern
i am learning django for some days and i feel overwhelm by slashes using in url pattern like path("login" , login , name='login') sometimes we use slash in the starting , sometime in the end and sometime we use at both side like this (/login, login/, /login/).it is really very confusing question = 1-what are these slashes and what does it do in my pattern 2 - when sould i use slash - in starting , in end or at both side i don't know exactly when to use these slashes in url pattern so please guide me -
Postgresql query error, ERROR: there is no unique constraint matching given keys for referenced table "app_user_user"
I am using Django version 4.2 and I am facing this error while executing the migration file. I made no changes to Django's standard tables "app_user_user_groups" and "app_user_user_user_permissions". In this migration, I changed the primary key(id) field in the "app_user_user" table from int to bigint I used the following command to get the sql output of the related migrate file; python manage.py sqlmigrate app_user 0002_auto_20230607_1447 output; BEGIN; -- -- Alter field extra on user -- -- (no-op) -- -- Alter field id on user -- ALTER TABLE "app_user_user" ALTER COLUMN "id" TYPE bigint USING "id"::bigint; ALTER SEQUENCE IF EXISTS "app_user_user_id_seq" AS bigint; ALTER TABLE "app_user_user_groups" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_user_permissions" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_groups" ADD CONSTRAINT "app_user_user_groups_user_id_d117580e_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; ALTER TABLE "app_user_user_user_permissions" ADD CONSTRAINT "app_user_user_user_permissions_user_id_ec2823c7_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; my user model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( _('email address'), unique=True ) is_staff = models.BooleanField( default=False ) is_active = models.BooleanField( default=True ) identity = models.CharField( max_length=20, unique=True, null=True, blank=True, verbose_name=_('Identity') ) name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Name') ) last_name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Last … -
Django Image is not saving
I am working on a website, where you can upload a project. Each project contains a name, description, image and a deadline, that you can set. When i try to upload a project by pressing the "Save Project" button, i get redirected to my homepage, like i wanted to, but the image does not get saved, everything else does. I dont get a error message. Picture of trying to create a project: enter image description here Picture of the homepage after pressing "Save Project": enter image description here In models i defined two models, Project and Image. "Project" handels the project name, description, creation date and the deadline. "Image" contains an Imagefield and has a Foreignkey relationship with Project. Forms has a class called Projectform using a Modelform. I made it associated with the model Project. After that i made an inline formset factory using inlineformset_factory for the Project and Image models, so it can handle many images for one project. In view there are two functions. One of them is homepage which retrieves all projects from the database, passes them to project.html. Which then shows everything, such as name, image... The second function "create_project" handles both GET and POST … -
i want to run django project in vs code after clone it from githup but this error was appear,how can i solve this error? [closed]
I clone the django project from the githup but if i run it in vs code this error was appear (C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'D:\\adrois\\Django-Email-Sender\\manage.py': [Errno 2] No such file or directory) how can i solve it please my python file is python38 python 39 python 310 -
Showing user specific saved posts
So I'm somewhat of a beginner in Django. I am working with DRF and trying to create a saved posts page while implementing a filter to ensure that a suer only sees the posts he saved, but I tried the normal filter way and it's returning an empty list even though it is showing that there are saved posts in the saved posts table in the admin dashboard here is the code for reference: this is the serializer: class SavedPostSerializer(serializers.ModelSerializer): class Meta: model = SavedPost fields = ('id','post', 'profile', 'created_at', 'updated_at') and this is the Views: class SavedPostListCreateView(generics.ListCreateAPIView): queryset = SavedPost.objects.all() serializer_class = SavedPostSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] ordering_fields=['created_at'] def get_queryset(self): # Filter queryset to include only saved posts of the authenticated user return SavedPost.objects.filter(profile=self.request.user.profile) I looked everywhere before asking here but didn't really find a solution I even went to chatGPT as a last resort and still the same answer -
Rendering and using self-referencing model objects in nested format without duplicates in Django template
Hope you are doing well... I have a little misunderstanding in using self-referencing model objects in html template. models.py class MyNumber(models.Model): has_bro = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) numb = models.CharField(max_length=10) def __str__(self) -> str: return self.numb views.py def index(request): context = { 'numbers': MyNumber.objects.all() } return render(request, 'test_folder/test_file.html', context) Let's say I have objects like 1 which has referencing objects too like 1.1 and 1.2. To make it complex let's add also more objects like 1.1.1 and 1.1.2 which are referencing to 1.1. The question is how to get all objects in nested format using <ul></ul> HTML tag without duplicates, like: * 1 * 1.1 * 1.1.1 * 1.1.2 * 1.2 So far, I am getting this result (below) with my little knowledge: * 1 * 1.1 * 1.2 * 1.1 * 1.1.1 * 1.1.2 * 1.2 Help is appreciated! -
UNIQUE constraint failed: home_profile.user_id - Django
I am just trying to mix my Profile model with my User one. I was following this Django series: https://www.youtube.com/watch?v=KXunlJgeRcU&list=PLCC34OHNcOtoQCR6K4RgBWNi3-7yGgg7b I accidentally deleted one of my users, so I tried recreating them again and got this error: UNIQUE constraint failed: home_profile.user_id I tried solving the issue with this answer: https://stackoverflow.com/a/60282442/19641902 ... but it gave me another error: 'User' object has no attribute 'profile' Also when I create the users in the database manually, it automatically creates three-four profiles in the User section of my database. The following is the code after following the above StackOverflow answer models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create A User Profile Model class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") follows = models.ManyToManyField("self", related_name="followed_by", symmetrical=False, blank=True) def __str__(self): return self.user.username # Create Profile When New User Signs Up #@receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() # Have the user follow themselves user_profile.follows.set([instance.profile.id]) user_profile.save() post_save.connect(create_profile, sender=User) admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile # Mix Profile info into User info class ProfileInline(admin.StackedInline): model = Profile # Extend User Model class UserAdmin(admin.ModelAdmin): model = User # Just display … -
Reset Password by retrieving Email from Forget Password View django
in the following code when "forget password" runs it takes "email" input from the user and generates token, using that email and token the user can change their password but what i want is: the user only needs to enter "new_password" and "reconfirm_password" and not the email to change the password, the email should be get from "forget password view" the following code gives this error while executing: cannot access local variable 'email' where it is not associated with a value views.py class ChangePasswordView(APIView): def get(self, request, token, email): context = {} try: profile_obj = UserAccount.objects.filter( forget_password_token=token).first() if profile_obj: context['email'] = email else: return JsonResponse({'message': 'Invalid token.'}) except Exception as e: print(e) return JsonResponse({'message': 'An error occurred.'}) return JsonResponse(context) def post(self, request, **kwargs): try: context = {} profile_obj = UserAccount.objects.filter( email=email).first() if profile_obj: context['email'] = email new_password = request.data.get('new_password') confirm_password = request.data.get('reconfirm_password') email = request.data.get('email') print(new_password) if email is None: return JsonResponse({'message': 'No user email found.'}) if new_password != confirm_password: return JsonResponse({'message': 'Both passwords should be equal.'}) user_obj = UserAccount.objects.get(email=email) user_obj.set_password(new_password) user_obj.save() return JsonResponse({'message': 'Password changed successfully.'}) except Exception as e: print(e) return JsonResponse({'message': 'An error occurred.'}) @method_decorator(csrf_exempt, name='dispatch') class ForgetPasswordView(View): def post(self, request): try: data = json.loads(request.body) email = … -
Calling QuerySet.only() after union() is not supported
I'm a newbie to django here. I'm getting the following error on my django backend: Calling QuerySet.only() after union() is not supported The error producing code is the following : post_notification_target_users = Post.get_post_comment_notification_target_users(post=post, post_commenter=post_commenter).only( 'id', 'username', 'notifications_settings__post_comment_notifications') upon further inspection, the following code is related to it : def comment_post_with_id(self, post_id, text): Post = get_post_model() post = Post.objects.filter(pk=post_id).get() return self.comment_post(post=post, text=text) I searched where .union() is used with regards to the above and this is what I found : def get_participants(self): User = get_user_model() # Add post creator post_creator = User.objects.filter(pk=self.creator_id) # Add post commentators post_commenters = User.objects.filter(posts_comments__post_id=self.pk, is_deleted=False) # If community post, add community members if self.community: community_members = User.objects.filter(communities_memberships__community_id=self.community_id, is_deleted=False) result = post_creator.union(post_commenters, community_members) else: result = post_creator.union(post_commenters) return result and def get_post_comment_notification_target_users(cls, post, post_commenter): """ Returns the users that should be notified of a post comment. This includes the post creator and other post commenters :return: """ # Add other post commenters, exclude replies to comments, the post commenter other_commenters = User.objects.filter( Q(posts_comments__post_id=post.pk, posts_comments__parent_comment_id=None, ) & ~Q( id=post_commenter.pk)) post_creator = User.objects.filter(pk=post.creator_id) return other_commenters.union(post_creator) I read other stack posts of what is allowed and what isn't after using union() but i'm unable to arrive at the right way … -
Unable to create user -Django.conrib.auth
I am Trying to create a Login system using Django inbuilt django.contrib.auth.models.user i am not getting any error in the code all files are check, but when i am trying the save the user in the database i can't see the user which i created in the django admin panel i am getting all the details through html form and exxtracting that values in views.py, but even after migrations signup.html <form method="POST" action="home/"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required/> <input type="email" name="email" placeholder="Email" required/> <input type="password" name="password" placeholder="Password" required/> <input type="password" name="confirm_password" placeholder="Confirm Password" required/> <input type="submit" name="submit" value="Sign Up"/> </form> views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User # Create your views here. def signup(request): if request.method=='POST': username=request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') confirm_password=request.POST.get('confirm_password') the_user=User.objects.create_user(username=username,email=email,password=password) the_user.save() return render(request,'signup.html') def home(request): return HttpResponse('Login Successfull') This Is Django Admin Panel -
can't access to tenant schemas in Django-tenant
I'm having problems accessing tenant schemas. So far I have been able to create schemas and tenants in the database. I'm creating tenants using tenant.localhost (no port) as domain, for localhost testing. I have successfully created tenant superusers, but so far I can only get the public schema to work. i.e. login, admin, and all the views of the app. But when I try tenant.localhost:8000 where I run my local server, I can't get it to work. Hopefully someone can help me out here. Thanks in advance. # Please note that only the relevant sections of the settings.py file are included here. SHARED_APPS = ( 'django_tenants', # mandatory 'customers', # you must list the app where your tenant model resides in # Other shared apps ) TENANT_APPS = ( # your tenant-specific apps 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', # Other tenant-specific apps ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = "customers.Client" # app.Model TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': config('NAME'), 'USER': config('USER'), 'PASSWORD': config('PASSWORD'), 'HOST': config('HOST'), 'PORT': '5432', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) AUTH_USER_MODEL = "accounts.User" MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', # Other middleware ] … -
Given a SQL query, can we find django code that generated it?
Given a SQL query, can we find django code that generated it? (reverse engineering database query to django code e.g. opposite/reverse of following operation) q = Item.objects.all() print(q.query) Input = db query = "SELECT * FROM table.Item" Output = django code = Item.objects.all()