Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect to url instead of error message? "Direct assignment to the forward side of a many-to-many set is prohibited."
I wish if the object exists in the database the user would just be redirected to "watchlist" instead I get the error "Direct assignment to the forward side of a many-to-many set is prohibited. Use addedauction.set () instead.". def addtowatchlist(request, auctionurl): Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) if Watchlist.objects.get_or_create(owner=request.user, addedauction=auctionurl) == False: return redirect("watchlist") return redirect("watchlist") -
How can I do this same thing using DRF OrderingFilter?
I am hoping to order a model by a DateTimeField using the DRF OrderingFilter. I am able to do this manually but not with the DRF backend. I have the following ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ["status"] def get_queryset(self): qs = DropTemplate.objects.annotate(start_time=F("collectiontemplates__visible_start_time")).filter(author__id=self.kwargs["author_pk"]).distinct("id") if "ordering" in self.request.query_params: return drop_templates.order_by("author_droptemplate.id", f"{self.request.query_params['ordering']}") else: return drop_templates I am using the distinct("id") because this Annotated QuerySet contains DropTemplates in the response. How can I achieve the same thing with the OrderingFilter? When I attempt to do this with the following ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ["status"] ordering_fields = ["title", "start_time"] ordering = ["start_time"] def get_queryset(self): return DropTemplate.objects.annotate(start_time=F("collectiontemplates__visible_start_time")).filter(publisher__id=self.kwargs["publisher_pk"]).distinct("id") I get this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("publisher_droptem... ^ ) -
Gunicorn: UndefinedTable: relation "user" does not exist
Here is the scenario, I'm deploying the Django app on an ec2 instance. I'm following this guide Digitalocean deployment guide. when I run my app using python manange.py runserver 0.0.0.0:800 and access the admin portal via http://server-ip-address:8000. everything works fine. But when I run gunicorn --bind 0.0.0.0:8000 myproject.wsgi and try to access the admin page it gives me 500 server errors and exception: UndefinedTable: relation "user" does not exist LINE 1: ...r", "user"."is_staff", "user"."is_superuser" FROM "user" WHE... Setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt.token_blacklist', 'rest_framework_simplejwt', 'corsheaders', 'drf_yasg', 'django_extensions', 'src', 'communications', 'rest_framework', 'registration', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', ] WSGI_APPLICATION = 'apbackend.wsgi.application' AUTH_USER_MODEL = 'registration.User' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser' ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } registration.models.py from django.db import models # Create your models here. import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import … -
Selenium webdriver.Remote() can't click on elements
Situation I'm using the Selenium Remote webdriver to do my tests on a Django project. I have several Docker containers, which is why I needed to use the Remote driver. Problem Thing is, the Selenium and Django project containers are connected properly and I am able to perform tests, but whenever I try the click() method on any element, I get the error Element <...> could not be scrolled into view However, by searching around I found out that doing self.driver.execute_script("arguments[0].click();", element) instead does work. I've read somewhere that it might be a problem that some part of the website is not loaded yet when Selenium attempts to click(), but that still doesn't tell me what to do. Any ideas? -
Django TestCase Delete without passing the article number in URL but as a value submit
How to delete article object in Django TestCase without passing it in URL delete/1/ im using <form action="{% url 'delete' %}" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit" name="article_id" value="{{ article.pk }}"> Delete </button> </form> urls.py path('delete/', views.delete, name='delete'), views.py @login_required(login_url='/login') def delete(request): article_to_delete = get_object_or_404( Article, id=request.POST.get('article_id')) if request.method == "POST" and request.user.is_authenticated: article_to_delete.delete() messages.success( request, ('Your article was successfully deleted!')) else: messages.warning( request, ('Something went wrong!')) return HttpResponseRedirect(reverse_lazy("home")) and my test_views.py def test_delete(self): self.client.login(username='mark', password='12345') I would like to make some good comparison for example self.assertEqual(response.status_code, 200) -
How can I Implement withdraw amount from investment balance using Django?
Here is my Model I have spent countless hours trying to implement "withdraw from investment" without success. print(investment.investment_return) shows the exact amount is being deducted but I don't know why its not updating total_available_balance from the dashboard. This is where I want the money to be deducted from total_available_balance = Investment.objects.filter(is_active=False).aggregate( total_available_balance=Sum('investment_return'))['total_available_balance'] from django.db import models from django.db.models import Max, Sum, F from datetime import datetime, timedelta class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 180 Days", "Basic - Daily 2% for 180 Days"), ("Premium - Daily 4% for 360 Days", "Premium - Daily 4% for 360 Days"), ) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) premium_interest = models.IntegerField(default=0, null=True) investment_return = models.IntegerField(default=0, null=True) withdraw_amount = models.IntegerField(default=0, null=True, blank=True) balance = models.IntegerField(default=0, null=True, blank=True) total_available_balance = models.IntegerField(default=0, null=True, blank=True) locked_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True) def save(self, *args, **kwargs): if self.plan == "Basic - Daily 2% for 180 Days": self.basic_interest = self.deposit_amount * 365 * 0.02/2 self.investment_return = self.deposit_amount + self.basic_interest self.due_date = datetime.now() + timedelta(seconds=5) else: self.premium_interest = self.deposit_amount*365*0.04 self.investment_return = self.deposit_amount +self.premium_interest self.due_date = datetime.now() + … -
Can't open file font error in xhtml2pdf template - django
style type="text/css"> @font-face {font-family: RTLFont; src: url('F:\MyProjects\my_app\app\static\app\fonts\font_name.ttf')} // Here body { font-weight: 200; font-size: 14px; font-family: RTLFont; } @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 40pt; } @frame content_frame { /* Content Frame */ left: 50pt; width: 512pt; top: 90pt; height: 632pt; } @frame footer_frame { /* Another static Frame */ -pdf-frame-content: footer_content; left: 50pt; width: 512pt; top: 772pt; height: 20pt; } } .text-header-primary { color: red; } getting me an error: TTFError at /api/visits/print Can't open file "C:\Users\User~1\AppData\Local\Temp\tmptiuhy3pp.ttf" -
best way to solve this use case in django ORM
I have a usecase that there is a user table and a skill table . 1 user can have multiple skills , for example writing , scalping , coding etc upto 50 so what is best way to save this ? from my search I came to conclusion that ManyToMany field is best here like this class Skill(models.Model): name = models.CharField(max_length=50) class User(models.Model): skills = models.ManyToManyField(Skill, blank=True, null=True) but while getting data I have to reverse queries aswell like getting all users having a specific skill for example writing . I am go on right way or not . please any help would be highly appreciated -
Does a using `.exists()` on a queryset with `.annotate()` runs the annotations?
So, I have this queryset where I run pretty heavy annotations , but I need to also check whether any data exists or not. So if I run exists() would the annotations be evaluated too? -
Data Analytics website using Django Python
I want to create a python project that uses mysql for database, django for the webframe. The website will contain a bunch of graphs fetched via different REST APIs and will create plots for the given data. I will be using docker to install all the dependencies (cython, numpy, pandas, matplotlib etc.) . Matplotlib will create the plots to be forwarded to the django website. The website will automatically update itself periodically as more data comes in over time (gathers new data from the APIs once a week maybe). To access the data the user will have to login with user credentials(login and password). Only a handful of people will be able to access the website so it is not dedicated to have a lot of traffic. I will be using Bluehost to host my django website in the end. I have never worked with web frames before would this be a hard task to accomplish. Are there easier ways to implement this? Open to any suggestions. Any problems I might face whilst developing ? -
why in redirecting url changes in the console but not in the browser (django)?
When redirecting the url in the console changes but not in the browser view.py def tables(request): if request.method == 'POST': text = request.POST.get('data_table') table_to_file(text) return redirect(reverse('result')) else: matrix = Matrix.objects.all() context = {'matrix': matrix} return render(request, 'methods/tables.html', context) def result(request): return render(request, 'methods/result.html') urls.py urlpatterns =[ path('result/', result, name = 'result'), path('tables/', tables, name='tables'), In console [20/Jun/2022 00:22:17] "POST /methods/tables/ HTTP/1.1" 302 0 [20/Jun/2022 00:22:17] "GET /methods/result/ HTTP/1.1" 200 571 But nothing changes in the browser -
Getting this error while trying to set SendGrid's email API with Django - AttributeError: 'str' object has no attribute 'get'
I am attempting to set up SendGrid with Django so that my website can send automated emails through SendGrid. So far, I haven't been able to send any emails. My settings are configured like this: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_BACKEND = 'sgbackend.SendGridBackend' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' with open(os.path.join(BASE_DIR, 'SENDGRID_API_KEY.txt')) as f: SENDGRID_API_KEY = f.read().strip() EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'dac@projectado.com' SENDGRID_SANDBOX_MODE_IN_DEBUG=True I'm attempting to run this code to send an email: message = Mail( from_email='dac@projectado.com', to_email='taylor.ryanc@gmail.com', subject='Sending with Twilio SendGrid is Fun', content='test123') try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) And I'm getting this error: 2022-06-19 15:42:18,726: Internal Server Error: /register/ Traceback (most recent call last): File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ryanctaylor/CTS/Registration/views.py", line 173, in register_view message = Mail( File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 31, in __init__ personalization.add_to(to_email) File "/home/ryanctaylor/.virtualenvs/cts-virtualenv/lib/python3.8/site-packages/sendgrid/helpers/mail/mail.py", line 319, in add_to self.tos.append(email.get()) AttributeError: 'str' object has no attribute 'get' Anyone know what I could be doing wrong here? Any help would be greatly appreciated. -
How can I Annotate() either by a related model @property OR with a reverse relation?
I have the following models: class DropTemplate(TimeStampedModel): author = models.ForeignKey(Author, on_delete=models.PROTECT) @property def start_time(self) -> Union[None, str]: earliest_collection = ( self.collectiontemplates.filter(drop_template_id=self.id, visible_start_time__isnull=False) .only("visible_start_time") .order_by("visible_start_time") .first() ) if earliest_collection is None: return None else: return earliest_collection.visible_start_time class CollectionTemplate(TimeStampedModel): drop_template = models.ForeignKey( DropTemplate, related_name="collectiontemplates", on_delete=models.PROTECT ) visible_start_time = models.DateTimeField(null=True, blank=True) And the following Django Rest Framework ModelViewSet: class DropTemplateViewSet(viewsets.ModelViewSet): serializer_class = DropTemplateSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] ordering_fields = ["start_time"] ordering = ["start_time"] def get_queryset(self): return DropTemplate.objects.annotate(start_time= # <-- WHAT DO I INPUT HERE? ).filter(author__id=self.kwargs["author_pk"]) I have already attempted to put a Subquery() in the get_queryset method since it seems I cannot directly utilize the @property since it is not on the DB layer.: def get_queryset(self): collection_templates = CollectionTemplate.objects.filter(visible_start_time__isnull=False).only("visible_start_time") return DropTemplate.objects.annotate(start_time=Subquery(collection_templates, output_field=DateTimeField())).filter(author__id=self.kwargs["author_pk"]) However, I get the following error: subquery must return only one column I'm new to Django Query Aggregation and have spent too much time trying to figure this out on my own. I'm hoping someone here can provide some guidance. Thank you! -
Django Queryset return None instead 0
I have a queryset in Django: puntos_jornalero1 = Equipo.objects.filter( jlg1__puntos__etapa=2 ).annotate( puntos_jornalero1=Sum('jlg1__puntos__puntos', default=0) ) If I make the queryset without the filter, I get 0 or the Sum correctly, but if I want to have the filter but in this case, when the result is 0, I get None. I need 0 because after that I need to Sum again the results. -
how to handle authentication in django for multiple apps and functionality
I know authentication should be global. all apps in a django project should serve the same purpose, but I am in a situation where I need to restrict some parts of the app to some users. I have a screen that allows you to access different app functionality .i.e personal spending to-do list e-mail scheduler/ report scheduler users should be able to see all apps, click on them, log in and then access different functionalities based on who they are. the views should also be different when they're an admin or just a simple user. how can this be achieved in django? is it with groups ? -
How to fix gettext() got an unexpected keyword argument 'null' in Django
I have a model, a serializer, and a view like below, model # get user model User = get_user_model() class Task(models.Model): "A task can be created by the user to save the task's details" COLOR_CHOICES = ( ("red", _("Red")), ("gre", _("Green")), ("blu", _("Blue")), ("yel", _("Yellow")), ("pur", _("Purple")), ("ora", _("Orange")), ("bla", _("Black")), ("whi", _("White")), ("ind", _("Indigo")), ("lim", _("Lime")), ("cya", _("Cyan")), ) title = models.CharField(max_length=150, blank=False, null=False, help_text=_("Enter your task's title"), verbose_name=_("title")) description = models.TextField(max_length=500, blank=True, null=True, help_text=_("Enter your task's description"), verbose_name=_("description")) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="utask", verbose_name=_("User")) time_to_start = models.DateTimeField(verbose_name=_("The time that the task should be started"), help_text=_("Enter the time that you want to start your task")) deadline = models.DateTimeField(verbose_name=_("The time that the task should be done"), help_text=_("Enter the time that you'll have done your task until it")) priority = models.IntegerField(choices=[(0, _("Not important")), (1, _("Low")), (2, _("Medium")), (3, _("High"))], default=1, verbose_name=_("Priority"), help_text=_("Choose the priority of your task")) color = models.CharField(max_length=3, choices=COLOR_CHOICES, default="whi", blank=True, null=True, verbose_name=_("Color"), help_text=_("Choose the color or the theme of your task")) notification = models.BooleanField(default=True, null=False, blank=True, verbose_name=_("Notification"), help_text=_("Do you want to receive a notification when the task is getting closer to the deadline or when it's passed that?")) def __str__(self): return self.title class Plan(models.Model): "A plan is a … -
NOT NULL constraint failed: posts_subscribe.firstname
I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button, I keep on getting the following error: NOT NULL constraint failed: posts_subscribe.firstname Here is my views.py def subscribe(request): if request.method == 'POST': firstname=request.POST.get('firstname') secondname=request.POST.get('secondname') email=request.POST.get('email') phonenumber=request.POST.get('phonenumber') en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber) en.save() return redirect('/') return render(request, 'subscribe.html') My models.py class Subscribe(models.Model): firstname = models.CharField(max_length=30, blank = True) secondname = models.CharField(max_length=30, blank = True) email = models.CharField(max_length=30) phonenumber = models.IntegerField() Here is my template {% extends 'index.html' %} {% block subscribe %} <div class="card mx-5"> <h1 class="mx-5 mt-3"> Subscribe</h1> <form method="POST" enctype="multipart/form-data" action="subscribe"> {% csrf_token %} <div class="mb-3 mx-5"> <label for="firstname" class="form-label ">First Name</label> <input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname"> </div> <div class="mb-3 mx-5"> <label for="secondname" class="form-label">Second Name (Optional)</label> <input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname"> </div> <div class="mb-3 mx-5"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control form-control-lg" id="email" placeholder="example@example.com"> </div> <div class="mb-3 mx-5"> <label for="phonenumber" class="form-label">Phonenumber</label> <input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678"> </div> <div class="mb-3 mx-5"> <button type="submit" class="btn-primary"> Subscribe</button> </div> </form> </div> {% endblock %} And my url patterns urlpatterns= [ path('', views.index, name='index'), path('subscribe', views.subscribe, name ='subscribe'), path('allposts', views.allposts, … -
Django 4.x - Conditional order_by of a QuerySet
The Objective The objective is to conditionally order a QuerySet by one of three different date fields in the view based on another field in the model. Since conditional ordering cannot be accomplished with Class Meta I am exploring accomplishing this objective in the view. Here is the relevant excerpt from models.py: READING_PROGRESS = [ ('---', '---'), ('1) On Reading List', '1) On Reading List'), ('2) Reading In Progress', '2) Reading In Progress'), ('3) Completed Reading', '3) Completed Reading'), ] class ReadingProgress(models.Model): record = models.ForeignKey( LibraryRecord, related_name='record_in_reading_progress', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Library record' ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) reading_progress = models.CharField( max_length=30, choices=READING_PROGRESS, default='---' ) date_added = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) date_started = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) date_completed = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) class Meta: ordering = [ 'reading_progress', ] verbose_name_plural = 'Reading Progress' unique_together = ('record', 'user',) # Record metadata date_created = models.DateTimeField( auto_now_add=True ) def __str__(self): return f'{self.record.title} - {self.reading_progress}' The relevant fields in the model are: reading_progress date_added date_started date_completed Each date field corresponds to a status value. I want to be able to order_by the QuerySet in the view by the field reading_progress: When reading_progress == '1) … -
Make json from audiofile by python for waveform
I changed wave/mp3 to json with this program. https://github.com/bbc/audiowaveform audiowaveform -i test.mp3 -o test.json This json works for showing the audioform. this json is like this , list of numbers, something like sampling...?? {"version":2,"channels":1,"sample_rate":44100,"samples_per_pixel":256,"bits":16,"length":5090,"data":[-20873,7262,-18598,26482,-13960,24194,-23076,3223,-12630,9770,-5839,17146,-3843,15499,-18422,3016,-14348,10706,-5625,13476,-8492,6077,-7876,7949,-8651,11759,-5424,9001,-9093,13121,-7641,9079,-10181,9877,-9001,4323,-5322,12272,-10333,9653,-10368,8790,-10793,6460,-9629,10254,-4771,9144,-8782,5503,-5752,8029,-9959,5774,-7144,8220,-11004,7199,-9145,7306,-5096,8332,-9930,3956,-5333,8168,-7351,7254,-7515,7378,-9147,10247,-8226,5130,-4069,9229,-6821,4259,-3569,8908,-11316,7191,-11041,14220,-8429,12541,-11705,14970,-9908,13398,-12572,10855,-10676,13266,-8604,6577,-8318,8095,-13359,12057,-9709,7556,-6081,8561,-8062,5234,-4988,6821,-7739,7500,-9188,8139,-2619,7234,-7794,6233,-4604,8059,-7197,4767,-7006,8878,-5750,5308,-5475,4398,-6693,94..... Now I want to do the equivalent thing in django/python. Is there any good method or library?? -
Getting the original language or original text of date in Excel file
I have a Django application where I give users a Excel file for them to give me dates, i ask them to give me the date in DD/MM/YYYY format (the one used in Latin America) The problem is that if the language of the Excel file is in English, it uses the MM/DD/YYYY format. So for example if they write 01/05/2022, when i open the file in my application i receive 05/01/2022. So I want to know if there is a way to get the original language of the excel file, for me to put some conditions inside my application, or if i can get the original raw text of the file. I can't change the format that the application uses (because I receive excel files that are mainly in the spanish language) or ask my clients to write the dates in a different format, or ask them to change the language of the file. I am open for other type of solutions too. -
Django: How to show a PointField in a map from a html template?
I have a Django class in my models.py, similar to the following: class MyClass(Model): .... description = TextField() location = PointField() In my views.py: template = loader.get_template('my_class.html') context = { 'my_class': MyClass.objects.filter(....), } return HttpResponse(template.render(context, request)) Finally, from my my_class.html template I can easily print each of the properties in my MyClass object: {{ my_class.description }} But {{ my_class.location}} just prints something like POINT (-13.716858926262476 50.42083468131796). Is there an easy way to show the point in an OpenStreetMap map? (Similar to the map in the admin page when using OSMGeoAdmin) Do I need to create a form for that if this template is read-only? (I dont need to edit any of the fields) (I'm using Django 3.2 in case that is important) -
ModuleNotFoundError: No module named 'I4G022709FMQ'
i am working on a django project and this error pops up when i run python manage.py runserver i've tried the solutions of some related questions but they arent working. 'I4G022709FMQ' is the name of my project in which i installed django with startapp command created blog app. the first part of the error message when i ran manage.py the end part of the error message -
Password reset timeout djoser jwt
In django default authentication system there's an option called PASSWORD_RESET_TIMEOUT Which expiers the reset password link after a specific time. I have an authentication system based on djoser and simplejwt I wanted to know if there is an option like django's PASSWORD_RESET_TIMEOUT in djoser. And if there is, how should i declare that in my code? -
Django Validation Check Positive value Python
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-d') or 0) if a ==b==c==d==0: continue if (a + b) > 0 and (c + d) > 0: raise ValidationError( "When A ,B is postive then positive C,D value is not allowed ") -
sitemap.xml <loc>https://example.com/?val1=1&val2=1</loc>
i did follow Django Sitemap Tutorial to create a sitemap.xml with GenericSitemap. That work good for Blog, But i need to add more links like: https://example.com/?author=NAME&taq=TAQ&Category=category and add link only if there is result for all 3 parameters author taq category models.py class Main_Category(models.Model): name = models.CharField(max_length=200, verbose_name=_("Main_Category")) class Tag(models.Model): name = models.CharField(max_length=200, verbose_name=_("Tag")) class Category(models.Model): name = models.CharField(max_length=200, verbose_name=_("Category")) Main_Category = models.ForeignKey(Main_Category, on_delete=models.CASCADE, null=True, blank=True) class Blog(models.Model): title = models.CharField() author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) main_Category = models.ForeignKey(Main_Category, on_delete=models.CASCADE) taq = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True, blank=True)