Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save method or post_save signal is not being called while through model instance of a ManyToManyField is getting created
I have a Post model in my Django app. It has a many-to-many relationship with User model through the UserTag model named user_tags. class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() user_tags = models.ManyToManyField(User, through=UserTag) class UserTag(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True, blank=True) def save(self, *args, **kwargs): print("#### user tagged ##### - save method") print(self.user) return super().save(*args, **kwargs) @receiver(post_save, sender=UserTag) def user_tagged_signal(sender, instance, created, **kwargs): if not created: return print("#### user tagged ##### - post save signal") print(instance.user) When I tag a user to a post as follows: post.user_tags.set(users) or post.user_tags.add(user) UserTang model instance gets created but save method or post_save signal of the UserTag model is not getting called. I want to send notification to the user and remove the notification depending on the creation and deletion of the UserTag instance. Is there anything I'm doing wrong or please suggest me a solution? -
HttpResponseRedirect and other redirect issues
I wrote simple web application, which can allow users upload and download files and make publications. I'm using django 5.0.1 and python 3.10.2. All worked correctly on my localhost server on my pc, but when i uploaded my project to web hosting (timeweb) i noticed that i cant login into admin panel and my account system. I'm getting infinity page loading and nothing. I have redirection from view of adding publication to the view of this publication after uploading and i'm getting the same issue here (publication still creates, but i cant redirect to it). But i can redirect from here to the older publications, so i think there is something with redirection to recently updated data in database. my def add and detail in views.py def detail(request, publication_id): auth = request.user.is_authenticated grade5 = Publication.objects.get(pk=publication_id).grade5 grade6 = Publication.objects.get(pk=publication_id).grade6 grade7 = Publication.objects.get(pk=publication_id).grade7 grade8 = Publication.objects.get(pk=publication_id).grade8 grade9 = Publication.objects.get(pk=publication_id).grade9 grade10 = Publication.objects.get(pk=publication_id).grade10 grade11 = Publication.objects.get(pk=publication_id).grade11 lettera = Publication.objects.get(pk=publication_id).lettera letterb = Publication.objects.get(pk=publication_id).letterb letterv = Publication.objects.get(pk=publication_id).letterv letterg = Publication.objects.get(pk=publication_id).letterg letterd = Publication.objects.get(pk=publication_id).letterd letter = (lettera*"А") + (letterb*"Б") + (letterv*"В") + (letterg*"Г") + (letterd*"Д") grade = (grade5 * "5") + (grade6 * "6") + (grade7 * "7") + (grade8 * "8") + (grade9 * "9") … -
Django - Stripe - Updating Model Field After Successful Purchase?
I’m currently building a gaming app where logged in users purchase our digital coins to play games and unlock features. I have Stripe installed alongside the Stripe webhook and that works correctly so users can currently purchase coins. I can get successful payments and see them through the Stripe application with zero issues. What I want to do next is update the model field named bankroll after a successful payment. So when a logged in user purchases lets say 2,000 coins for $100.00 then the bankroll field gets updated. How can I do that with my current code? I can’t really get this to fully work how I want from what I’ve been testing. The UserInfo model contains basic user information. The Price and Product models are in reference to the Stripe product. The value of coins to the Stripe product is referenced in the credits field in the Price model. The price of each credits is referenced in the price field in the Price model. Screenshots below as well as my code. bankroll admin stripe-product-admin coins modal on front end Any help is gladly appreciated! Thanks! models.py class UserInfo(models.Model): bankroll = models.IntegerField(default=0) def get_display_price(self): return "{0:.2f}".format(self.bankroll / 100) class … -
Javascript Bootstrap Spinner Visible on submit
It's a Django project. I got this Bootstrap spinner in a span in a button: <form method="POST" id="pdfUploadForm" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit" id="submitButton"> <span id="spinner-box" class="spinner-border spinner-border-sm not-visible" role="status" aria- hidden="true"></span> Submit... </button> </form> And that CSS. .not-visible { display: none; } I'm removing the class "not-visible" in javascript: document.getElementById('pdfUploadForm').addEventListener('submit', async (e) => { e.preventDefault(); console.log(document.getElementById('spinner-box').classList); document.getElementById('spinner-box').classList.remove('not-visible'); console.log(document.getElementById('spinner-box').classList); document.getElementById('submitButton').innerText = 'Processing...'; From the console log the class is successfully removed. But the spinner is still NOT displaying. And i can't get why... Thanks!! -
(admin.E202) <model> has no ForeignKey to <model> With OneToOne Field Django Admin Tool
I have a small app with these two models: class LocationSpecialNeeds(models.Model): [some fields] class Location(models.Model): [some fields] location = models.OneToOneField(LocationSpecialNeeds, on_delete=models.CASCADE) Which I want to see in the Django admin tool using this code: from django.contrib import admin from .models import Location, LocationSpecialNeeds class LocationSpecialNeedsInline(admin.StackedInline): model = LocationSpecialNeeds can_delete = False @admin.register(Location) class LocationAdmin(admin.ModelAdmin): inlines = [ LocationSpecialNeedsInline, ] Which seems straightforward enough. However, I get the error: <class 'locations.admin.LocationSpecialNeedsInline'>: (admin.E202) 'locations.LocationSpecialNeeds' has no ForeignKey to 'locations.Location'. When I start the app. Isn't a OneToOne a foreign key relationship? What am I missing? -
Choosing frameworks for creating the platform for students
I wanna create a platform as a project for my university. Here are main features: the teacher can create tests and run them at specific times students are limited in time and can pass tests (each test has got it's own time limit) there is an overall student ranking on the home page the teacher can publish the homework What should I choose? I am thinking about Django + React. What would you recommend? -
I can't receive tokens on android app from the django server
I am trying to figure out why I can not receive access tokens on my android app from the django server. The android app structure seems fine to me. Still the issue persists. I tested the server response with postman and it looks fine (I receive both, access and refresh tokens) but on my android app that does not work. I share with you some code snippets hoping someone here could help me. Thank you in advance anybody! LOGIN FUNCTION suspend fun loginUser(userService: UserService, email: String, password: String, context: Context, navController: NavController) { try { val response = userService.loginUser(UserLoginRequest(email, password)).await() if (response.isSuccessful) { val tokenResponse = response.body()!! TokenManager.saveTokens(tokenResponse.accessToken, tokenResponse.refreshToken) withContext(Dispatchers.Main) { navController.navigate(Screen.FeedScreen.route) } } else { withContext(Dispatchers.Main) { Toast.makeText(context, "Login failed: ${response.message()}", Toast.LENGTH_LONG).show() } } } catch (e: Exception) { withContext(Dispatchers.Main) { Toast.makeText(context, "An error occurred: ${e.localizedMessage}", Toast.LENGTH_LONG).show() } } } TOKEN MANAGER package com.example.events.util import android.content.SharedPreferences import android.util.Log import com.example.events.network.NetworkModule import com.example.events.network.RefreshRequestBody import com.example.events.network.RefreshTokenResponse import com.example.events.network.TokenRefreshService import com.google.gson.Gson object TokenManager { private lateinit var preferences: SharedPreferences // Initialise with SharedPreferences fun init(preferences: SharedPreferences) { this.preferences = preferences } val accessToken: String? get() = preferences.getString("access", null) fun isTokenExpired(): Boolean { val expiry = preferences.getLong("expiry", 0) return expiry < System.currentTimeMillis() } … -
How to enable dynamic custom domains
I am a developer for a SAAS web app and excel plugin. With our product, users are able to share outputs of their work with third parties via a browser link. The format of the browser link today is nameofourwebsite.io/titleofoutput. I'm looking to implement two versions of a feature: As a V1, I'd like to enable users to create a custom domain in the form of companyname.website.io/titleofspreadsheet. I am already the owner of the domain website.io. As a V2, (to be implemented at a later date), I'd like for users to be able to bring their own custom domain, similar to the implementation with Stripe (https://docs.stripe.com/payments/checkout/custom-domains). In other words, when a user shares a browser link to the output of their work instead of the link being companyname.website.io/titleofspreadsheet the browser link would be something along the lines of customprefix.companywebsite.com/titleofworkbook. I am not sure how to tackle this problem and I am looking for advice as to the steps we need to take. -
How to ensure changes to variables in .env file reflect in Django project?
I'm encountering an issue in my Django project where changes made to variables in the .env file do not seem to be reflected when I restart the server. Here are the steps I've taken: Verified that the .env file is in the correct location and its name is exactly .env. Restarted the Django development server after making changes to the .env file. Double-checked the syntax of the .env file for any errors or typos. Cleared the cache after making changes to the .env fil (using python manage.py clear_cache) -
In Django, is it possible to use reverse/redirect with a view function (not string) as a to parameter, when using namespaces?
I'm trying to get reverse (via redirect) to work in the context of namespaces and when using view functions. This fails with a NoReverseMatch, somewhat to my surprise. In principle, I'd say that it's out-figurable in an automatic way what I mean. When using this without app_name = ... this works fine. Is this a bug (or simply unsupported)? Or is there a way it could be made to work? # urls.py from django.urls import path from .views import some_other_view, some_view app_name = 'foo_app' # here the app namespace is defined urlpatterns = [ path('some_other_view/', some_other_view), path('some_view/', some_view), # ... ] # views.py from django.shortcuts import redirect def some_other_view(request): return redirect(some_view) # note that the view is simply passed as a function here, not as a string. def some_view(request): # ... actual view here -
Send data from one table to another when instantiated django
What I want is that when creating an instance of the user object the name goes to another table called profile_data but I don't know how to do it, can someone help me? -
Django and django-mssql - problem with rendering ForeignKey field in ModelForm
In my Django application I would like to use 2 databases. First (default one) - sqlite3 and second MS SQL. Since Django don't support MsSQL I'm forced to use 3rd party django-mssql package. I have model with ForeignKey and ModelForm based on this model. The problem is that I get an error "no such table: TLC_OWDP_InstructionParameters" while trying to render ForeignKey form field. It looks like django tries to find the table in wrong database. I tried use PostgreSQL instead of MS SQL and everything works fine. Could someone please help me with this issue? My code below: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'logistyka': { 'ENGINE': 'mssql', 'NAME': 'LOGISTYKA', 'HOST': 'WPLRZD0A', 'PORT': '', 'USER' : '***', 'PASSWORD' : '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } models.py class InstructionParameter(models.Model): id = models.AutoField(db_column='id', primary_key=True) instr_number = models.CharField(max_length=30, verbose_name='Numer instrukcji') tab_number = models.SmallIntegerField(verbose_name='Numer tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) point_number = models.SmallIntegerField(verbose_name='Numer punktu tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) def __str__(self): return f'{self.instr_number} tab.{self.tab_number} p.{self.point_number}' class Meta: verbose_name_plural = 'Instrukcje' managed = False db_table = 'TLC_OWDP_InstructionParameters' class PartParameter(models.Model): id = models.AutoField(primary_key=True) part_number = models.CharField(max_length=30, verbose_name='Numer części') op_number = models.CharField(max_length=4, verbose_name='Numer operacji') instruction_id = models.ForeignKey('InstructionParameter', to_field='id', db_column='instruction_id', … -
one of many python attributes not carrying over to children in GitHub class, with and without Django support
When i subclass my GitHubIssues class (see below), all the children have the expected attributes EXCEPT self.repo_object... when i redeclare it in child classes, it functions as it should... but i shouldn't need to do this if my knowledge of inheritance is correct. class GitHubIssues: class UnknownRepositoryError(UnknownObjectException): ... def __init__(self, repo_name: str, github_key_path: str, data: dict = None): # TODO: test this as standalone more. self.repo_name = repo_name self.repo_obj = None self._IsDjangoForm = None self._GitHubKeyPath = github_key_path self._GitHubKey = None self._IsInIssues = None if not self.IsDjangoForm: self.data: dict = data self.cleaned_data: dict = self.data self.errors: list = [] self.repo_obj = self.GetRepoObject() # other attributes omitted for brevity def GetRepoObject(self): try: g = Github(self.__GitHubKey) for repo in g.get_user().get_repos(): if repo.name == self.repo_name: self.repo_obj = repo return self.repo_obj except BadCredentialsException as e: self.add_error(None, e) except GithubException as e: self.add_error(None, e) except Exception as e: self.add_error(None, e) if isinstance(self.repo_obj, Repository.Repository): pass else: try: raise self.UnknownRepositoryError(404, data=self.repo_obj, message=f"Could not find {self.repo_name}") except self.UnknownRepositoryError as e: self.add_error(None, e) class BugReportForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._issue_added = None if kwargs: if 'repo_name' in kwargs: self.repo_name = kwargs['repo_name'] else: self.repo_name = 'BackflowPreventionValveCatalog' if 'GitHubKeyPath' in kwargs: self._GitHubKeyPath = kwargs['GitHubKeyPath'] else: self._GitHubKeyPath = #redacted path else: … -
I created a new model and registered it to admin.py but when I am running python manage.py makemigrations it showing that no migrations to apply
In models.py: from colorfield.fields import ColorField class colour(models.Model): color=ColorField(format="hexa") def __str__(self): return str(self.id) In admin.py: admin.site.register(colour) When I am running python manage.py makemigrations it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected And when I am running python manage.py migrate it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Now When I am going to admin pannel there is a table called colour but when I am clicking it there is an no such table: core_colour error -
Containerized Django application works on local, but not on GKE
Any containerized Django applications work in local, but only return "no healthy upstream" when run on GKE. I tried with this django example: https://github.com/mukulmantosh/cloud-code-helloworld on which I only commented out the mysqlclient in the requirements.txt file. In GKE the application runs behind an ingress internal load balancer (I have no access to Cloud Run for some corporate reason). What I get in local mode: (base) C:\Users\path\to\app>docker run -p 8080:8080 helloworld:1 [21/Feb/2024 10:54:17] "GET / HTTP/1.1" 200 3968 [21/Feb/2024 10:54:17] "GET /static/KE-hello-world.svg HTTP/1.1" 200 116030 [21/Feb/2024 10:54:17] "GET /static/cloud_bg.svg HTTP/1.1" 200 7213 [21/Feb/2024 10:54:17] "GET /static/kubernetes-engine-icon.png HTTP/1.1" 200 6967 [21/Feb/2024 10:54:19] "GET / HTTP/1.1" 200 3968 What I get in the Workload logs on GCP: 2024-02-21 12:03:40.613 CET Not Found: / 2024-02-21 12:03:40.613 CET [21/Feb/2024 11:03:40] "GET / HTTP/1.1" 404 2272 -
Error when starting Django React app with npm start: "Invalid options object" ( 'Something is already running on port 5432' )
`I have a Django-React application with PostgreSQL/MySQL. The app was working fine, until today I attempted to start my frontend using npm start. This is the first time I've encountered the following prompt: ? Something is already running on port 5432. Would you like to run the app on another port instead? » (Y/n) Opting for 'Y' leads to the subsequent error: Would you like to run the app on another port instead? ... yes Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. options.allowedHosts[0] should be a non-empty string. I haven't made any recent changes or installations. What should I do ? I tried to change the start script in the package.json to "start": "set PORT=3000 && react-scripts start", but that didn't work. Additionally, I deleted node_modules, package-lock.json, and ran npm install, but I still got the same error message. -
python Django Field 'id' expected a number but got '{"isTrusted":true}'
mistake:Field 'id' expected a number but got '{"isTrusted":true}' When I attempt to perform the delete operation, an error is being reported, and I'm unsure how to resolve it. view.py class ClassAdminAPI(APIView): @validate_serializer(CreateClassSeriaizer) @super_admin_required def post(self, request): class_data = request.data class_data["title"] = class_data.get("title") class_data["start_time"] = dateutil.parser.parse(class_data["start_time"]) class_data["end_time"] = dateutil.parser.parse(class_data["end_time"]) class_data["created_by"] = request.user if class_data["end_time"] <= class_data["start_time"]: return self.error("Start time must occur earlier than end time") user_data = class_data.pop("users") try: with transaction.atomic(): if Class.objects.filter(title=class_data["title"]).exists(): return self.error("Class with the same title already exists") class_obj = Class.objects.create(**class_data) for data in user_data: if len(data) != 4 or len(data[1]) > 32: return self.error(f"Error occurred while processing data '{data}'") username = data[1] + data[2] user, created = User.objects.get_or_create(username=username, defaults={ "password": make_password(data[1]), "college": data[3], "student_number": data[1] }) if created: profile = UserProfile(user=user, real_name=data[2]) profile.save() class_obj.users.add(user) return self.success(ClassSerializer(class_obj).data) except IntegrityError as e: return self.error(str(e).split("\n")[1]) @super_admin_required def get(self, request): class_id = request.GET.get("id") if class_id: try: class_obj = Class.objects.get(id=class_id) ensure_created_by(class_obj, request.user) return self.success(ClassSerializer(class_obj).data) except Class.DoesNotExist: return self.error("Class does not exist") classes_obj = Class.objects.all().order_by("-create_time") # print("classes_obj:", classes_obj) if request.user.is_admin(): classes_obj = classes_obj.filter(created__by=request.user) print("classes_obj:", classes_obj) return self.success(self.paginate_data(request, classes_obj, ClassSerializer)) @super_admin_required def delete(self, request): Class_id = request.GET.get("id") if not Class_id: return self.error("Invalid Parameter, id is required") class_ids = Class_id.split(",") if Class.objects.filter(id__in=class_ids, created_by=request.user).exists(): return self.error("Current … -
Getting Forbidden (403) CSRF verification failed
I am using Django, DRF , docker, Nginx and AWS EC2 instance for my personal project, application is working fine when it is using HTTP , once i changed to HTTPS i am getting CSRF Verification Failed. used {% csrf_token %} where required in html forms in settings.py CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['http://localhost/', 'example.co.in', 'www.example.co.in'] CORS_ORIGIN_WHITELIST = ['http://localhost/', 'example.co.in', 'www.example.co.in'] Please help me in solving this issue, thank you everyone -
Zegocloud video call Recording issue
How to record video calls using zegocloud,i have created the server call backurl in the admin console but when i call the start record api endpoint of zegocloud its not start recording,Can any body help me to resolve the issue? -
Problem returning context_processor data to html for looping
I'm trying to add categories field to navigation. So far I've made context_processor which querys all the car brands. In my navigation I'm loopin all of the brands and this works. I also want to add dropdowns which contains certain car models for certain car brands. I think the problem lays in returning right data, that is loopable in my _base.html. _base.html <div class="flex pt-3 container w-full"> {% for item in car_brands %} <button id="dropdown-button" data-dropdown-toggle="dropdown-{{item.id}}" class="py-2.5 px-4 text-sm font-medium text-center text-gray-900 bg-gray-100 uppercase" type="button">{{item}}</button> <div id="dropdown-{{item.id}}" class="hidden shadow w-44 bg-gray-100"> <ul aria-labelledby="dropdown-button"> {% for model in models %} <li> <a href="#" class="inline-flex w-full px-4 py-2 hover:bg-gray-50">{{ model }}</a> </li> {% endfor %} </ul> </div> {% endfor %} context_processors.py from .models import CarBrandCategory, CarModel def brand_catalogue(request): car_brands = CarBrandCategory.objects.all() for brand in car_brands: models = [model for model in CarModel.objects.filter(brand_id=brand.id)] print(models) return { 'car_brands': car_brands, 'models': models } If printing, it will give me different lists, consists of different models, eg. [<CarModel: X4>, <CarModel: X5>, <CarModel: 3. Seeria>] [<CarModel: A4>, <CarModel: A6>, <CarModel: A8>] [<CarModel: C klass>, <CarModel: S-Klass>] I was wondering if anyone has experience with this kind of solutions and what could be the most optimal way to … -
Django Rest Framework Pagination isn't working
My settings.py: 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'authentication.authentication.ExpiringTokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } My views.py: permission_classes = [IsAuthenticated] queryset = Post.objects.all().order_by('-id') serializer_class = PostSerializer pagination_class = PageNumberPagination The code should show 10 result in each page. But it's showing all the 13 result. The result is like this: { "count": 13, "next": null, "previous": null, "results": [ { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_SJpZeBc.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_Fs2qSAY.webp", "order": 2 } ], "caption": "my name is ayon", "created_at": "2024-02-21T09:40:46.069468Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_AvXbLoq.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_lRnFcgd.webp", "order": 2 } ], "caption": "friends will be great", "created_at": "2024-02-21T09:40:40.146627Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_XcnIJ6o.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_MPj4huO.webp", "order": 2 } ], "caption": "friends", "created_at": "2024-02-21T09:40:36.631495Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_LdvliP2.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_nLRwhrS.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:33.934885Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_iFAk1XG.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_EEnnvOX.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:27.121978Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_IrIuNi9.jpeg", "order": 1 }, { … -
email activation failing in django
how im sending the activation email current_site = get_current_site(request) email_subject = 'confirm your email !' message2= render_to_string('authentication/emailConfirmation.html',{ 'name':user.first_name + user.last_name, 'domain':current_site.domain, 'uid':urlsafe_b64encode(force_bytes(user.pk)), 'token':generate_token.make_token(user)}) email= EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [user.email], ) email.send() the activate view from django.core.mail import send_mail ,EmailMessage from django.http import Http404, HttpResponse from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes , force_str from django.utils.http import urlsafe_base64_decode from . tokens import generate_token def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link")``` the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator()``` the confirmation email template {% autoescape off %} Confirmation Link: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} whenever i click on the confirmation link it automatically fails -
Django admin: exclude values from dropdown while keeping existing value
I have a site with conference rankings, where FoR codes are one of the fields. The database includes old FoR codes that are no longer used. I'd like to exclude these codes from the dropdown menu of the change form on the admin site, as it takes some scrolling to reach the current codes (screenshot). I tried excluding the old codes by overriding formfield_for_foreignkey, as seen in the below code snippet. However, if a conference entry with an old code is opened in the admin site, then the FoR code dropdown is cleared (screenshot). Is it possible to exclude the old FoR codes while still preserving the FoR code for old entries? In the example I linked above (1, 2), I want to preserve the 0905 code for this old entry, while only showing the current codes for new entries. class RankInline(admin.TabularInline): model = Rank extra = 1 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "for": kwargs["queryset"] = ForCode.objects.filter(code__startswith="46") return super(RankInline, self).formfield_for_foreignkey(db_field, request, **kwargs) class CommentInLine(admin.TabularInline): model = Comment extra = 0 class ConferenceAdmin(admin.ModelAdmin): list_display = ("acronym", "title", "url") list_display_links = ("acronym", "title", "url") search_fields = ("acronym", "title", "url") inlines = (RankInline, CommentInLine) -
How to connect from mobile phone to the localhost
I am developing a website on Django, the local version is run by development server (python manage.py runserver) on localhost. I can test my site in a browser, the address is http://127.0.0.1:8000/. But now I need to see how my website is looking on the mobile phone. My laptop OS is Linux Mint, the phone OS is Android, both are connected to the WiFi router. I tried this recipe. I found out my WLAN IP (by the command ifconfig), which happens to be 192.168.0.104. By the recipe, I should enter the address together with port number, which is, apparently, 8000 (according to the development server port, see the paragraph 1), so I should see my local website by the address 192.168.0.104:8000, both from the laptop and the phone browser. However, in both devices I get a following error (translated to English): Can not connect. Firefox cannot establish a connection to the server at 192.168.0.104:8000. The site may be temporarily unavailable or too busy. Please try again in a few moments. If you cannot load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure Firefox has permission to access … -
How to using multi router in django?
Currently, I'm using the Django Framework and have a large data block, a router. In Django Framework, how can I split data into subdatabases and use multiple routers??? I want to split the block of data into several parts. Thanks.