Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django form field queryset to selected user
I have a list of users, when i click an user a form is created with user, area and room fields. I want to have the user field to be the one that was created and to be non editable. My implementation sets the initial data user to be the one that was clicked, but I can edit it and I get all users. If I disable field, then it is not counted when form is saved, so I get the error that the object cannot be saved because user is not provided. # user detail view class UserDetailView(LoginRequiredMixin, FormMixin, DetailView): model = TbUser form_class = TbPeopleEntranceRightForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() context['user_terminal_permissions'] = TbTerminalPermission.objects.filter( user=super().get_object()) context['user_entrance_rights'] = TbPeopleEntranceRight.objects.filter( user=super().get_object()) context['people_entrance_rights'] = TbPeopleEntranceRight.objects.all() context['rooms'] = TbRoom.objects.all() context['form'] = TbPeopleEntranceRightForm( initial={'user': self.object}) return context def get_success_url(self): return reverse_lazy('user-detail', kwargs={'pk': self.object.id}) def get_form_kwargs(self): kwargs = super().get_form_kwargs() obj = self.object user = TbUser.objects.filter(id=obj.id) #kwargs.update({'user': user}) kwargs['user'] = user return kwargs def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() print("posting") if form.is_valid(): print("valid") form.save() return self.form_valid(form) else: print("invalid") print(form.errors) return self.form_invalid(form) # form class TbPeopleEntranceRightForm(forms.ModelForm): # user = forms.ModelChoiceField( # queryset=TbUser.objects.none(), required=False) area = forms.ModelChoiceField( queryset=TbArea.objects.none(), to_field_name="name") … -
TimeField returning None in Django
I have an existing database I need to pull data from the timestamp field in Django. I created the Django model as a TimeField, but when I query the data I get 'None' instead of the data in the timestamp field. From my model class: (there is more in the model, I just condensed this for readability) class Report(models.Model): upload_time = models.TimeField() date = models.CharField(max_length=9) @staticmethod def get_reports(**query): reports = Report.objects.order_by('date').filter(query) for report in reports: print(report.upload_time) In my views.py I have a method that checks for the date I am looking for to pull all reports from that date. The database saved the date as a string, so I get that ok, then just turn it into a datetime object and call my get_reports method by passing the date into it. It works to get everything from the report except the timestamp. What am I missing? -
How to make a Timer exactly 30 seconds from created date Django
I need to make an operation only available in 30 seconds, and then it expires. I Have this model: (operation) status = CharField(max_length=10, default="INI") created_at = DateTimeField(auto_now_add=True) account = ForeignKey(Account, null=False, on_delete=CASCADE) metadata = models.JSONField(default=dict) external_ref = CharField(max_length=128) expires_at = DateTimeField(default=timezone.now()+timezone.timedelta(seconds=30)) I wanna be able to create in the expires_at field, a timestamp with exactly 30 seconds from the created_at Date, it is like a timeout function, but when I run the test: def test_timeout_is_30_seconds(self): print(self.operation.created_at) timer = self.operation.created_at + timezone.timedelta(seconds=30) print(timer) self.assertEqual(self.operation.expires_at, timer) it fails with this message: AssertionError: datetime.datetime(2021, 6, 22, 19, 0, 42, 537490, tzinfo=<UTC>) != datetime.datetime(2021, 6, 22, 19, 0, 45, 844588, tzinfo=<UTC>) I dont know if I need to make an external function or method inside the class or directly in the View, but I would prefer this default behavior in the models so I dont need to worry about setting expiry dates I would be very grateful if you could help me solve it! :D any tips and information is appreciated -
main.js:95 WebSocket connection to 'wss://website' failed :(
I have tried to make a simple video calling app using Django and WebRTC. I tried running this on localhost and it works well, but I tried hosting it on a website hosting platform and now it doesn't work. I surfed through many websites to correct this, but failed. I haven't used Redis server. Here are some required files: asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myProject.settings') application = ProtocolTypeRouter({ "https": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['my hosting website url'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'channels', ] 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', ] ROOT_URLCONF = 'myProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Why am I getting an error with Django Rest Framework GenericViewSet?
I have been trying to figure out why I am having trouble with getting a list view from a GenericViewSet. It only happens on the list view. Other views seem to be okay. The error I get is this: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "api:user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. [22/Jun/2021 18:10:29] "GET /api/users/ HTTP/1.1" 500 183983 I have tried removing lookup_field = "username" and it still does the same thing. I'm just at a loss trying to figure out the cause of my problem here. Any help would be appreciated. Here is the model: # Override UserManager and allow login with both username and email address class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get( Q(**{self.model.USERNAME_FIELD: username}) | Q(**{self.model.EMAIL_FIELD: username}) ) class User(AbstractUser, TimeStampedModel): class Meta(object): unique_together = ('email',) email = EmailField(_('email address'), unique=True, blank=True, max_length=255) phone_number = PhoneNumberField(_('phone number'), blank=True) address = CharField(_("street address"), blank=True, max_length=255) city = CharField(_("city"), blank=True, max_length=255) state = USStateField(_("state"), blank=True) zip = USZipCodeField(_("ZIP code"), blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] # for allowing both username and email login objects = … -
How to limit query depth in strawberry-graphql (Django implementation)?
I have a nested structure in my strawberry-graphql schema resolver implementation. Any suggestion on how I can limit query depth in strawberry-graphql (Django implementation)? -
Updating a model using a dynamic serializer in Django Rest Framework
I set up a serializer that is able to dynamically serialize the desired fields as specified in the Django Rest Framework docs. class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} How would I set up the view to allow editing by post method? I tried something like this. views.py def post(self, request, pk, format=None): fields = form_fields_map[request.data['form_info']['index']]['main_info'] user = User.objects.get(pk=pk) user_serializer = UserSerializer(customer, request.data['main_info'], partial=True, fields=fields) if customer_serializer.is_valid(): customer_serializer.save() return Response(customer_serializer.data) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY) but I get this error. `update()` did not return an object instance. -
There are duplicate fields in 'fieldsets[4][1]' Django
Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[4][1]'. System check identified 1 issue (0 silenced). ^C% ~/Projects/Python/CRAFTMINE/web │ main !8 ?1 ✔ │ 25m 24s │ 10:44:26 ~/Projects/Python/CRAFTMINE/web │ main !8 ?1 python3 manage.py runserver INT ✘ │ 10:44:26 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[4][1]'. ``` I got this error but don't know what's wrong. My admin.py shows from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import … -
Any equivalent material for Django like this for rails: https://rebuilding-rails.com/
Rebuilding Rails is a fantastic resource to really be an expert on the rails framework. It basically teach you how to create a tiny, toy version of rails, so you can see how the framework works from the inside out. Anyone knows of a similar resource for Django? -
"user_id" is empty when setting MyForm(data=data) (Django)
I have the following model #models.py class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) link = models.URLField(max_length=2048) date_added = models.DateTimeField(default = timezone.now) used = models.BooleanField(default = True) and my form class MyModelForm(forms.ModelForm): class Meta: model = Wishlist exclude = [ "user","date_added" ] when I in my view try to "manually" create an instance and save it, the "user_id" in my database is NULL #views.py def AddLink(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyModelForm(request.POST,instance = instance) if form.is_valid(): link = form.instance.wishlist used = form.instance.discount_pct #some util function to do some stuff res = my_util_func(link,api_key) for used, link in zip(res[0],res[1]): data = {"link":link,"used":used} form = MyModelForm(data=data) form.save() context = { "results":res} return render(request, "discounttracker/myhtml.html",context=context) I have tried changing data to data = {"link":link,"used":used,"user":user} and data = {"link":link,"used":used,"user_id":user} but it is still empty. How can I add the user here? -
Django factories import classes from each other error
I had 2 factory classes: 1. from factories.data import BFactory class AFactory(factory.DjangoModelFactory): class Meta: model = A full_name = factory.Sequence(lambda n: 'Full name %s' % n) label = factory.Sequence(lambda n: 'lable-%s' % n) content = factory.SubFactory(BFactory) from factories.data import AFactory class BFactory(factory.DjangoModelFactory): class Meta: model = B full_name = factory.Sequence(lambda n: 'Full name %s' % n) label = factory.Sequence(lambda n: 'lable-%s' % n) content = factory.SubFactory(AFactory) When i run my code, seems like i got a circular imports, because 2 classes import each other. Do you have any suggestion ? Thanks -
Appending the logged-in User to Django REST framework POST model update
I've tried to follow this answer Django Rest Framework - Post Foreign Key but can't get it to work. A user POSTs the creation of an Event, but I cannot figure out how to configure the serializers to append the User foreign key constraint to associate Event with the User. models.py class Event(models.Model): created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) zone = models.CharField(max_length=1024, null=True) start_datetime = models.DateTimeField(null=True) runtime_seconds = models.IntegerField(default=60, null=True) user=models.ForeignKey(User, on_delete=models.CASCADE,default=None,null=True) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Event, self).save(*args, **kwargs) def __str__(self): return str(self.id) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['zone','start_datetime','runtime_seconds','user'] def to_representation(self, instance): self.fields['user'] = UserSerializer(read_only=True) return super(EventSerializer, self).to_representation(instance) views.py This feels janky--I making dog out of tee'ing up the merged event and user data but still not sure why it doesn't work. class EventCreateView(APIView): permission_classes = (IsAuthenticated,) serializer_class = EventSerializer def post(self, request): user_serialized = UserSerializer(request.user) payload={ **request.data, **user_serialized.data} pprint(payload) serializer_event = EventSerializer(data=payload) if serializer_event.is_valid(): pprint(serializer_event.validated_data) serializer_event.save() return Response(serializer_event.data, status=status.HTTP_201_CREATED) pprint(serializer_event.errors) return Response(serializer_event.errors, status=status.HTTP_400_BAD_REQUEST) Example POST {"id":"fc01ef4c-c05f-4416-ba10-dd0d779abddb","zone":"278c6def-beab-49a2-9876-ce3eef35a16e","start_date":"2021-06-10T06:00:00.000Z","start_time":"1:30 am","start_datetime":"2021-06-10T07:30:00.000Z","runtime_seconds":"333"} Output--missing user_id OrderedDict([('zone', '278c6def-beab-49a2-9876-ce3eef35a16e'), ('start_datetime', datetime.datetime(2021, 6, 10, 1, 30, … -
difference between django and django rest framework
Okay I just finished a YouTube course on Django tutorials and i more or less understand Django to an extent. Now the issue is Django rest framework. Google says its used to create APIs but i just dont get it. if the Django framework can be used to create web applications then what can Django rest framework be used for in terms of web application development. By this question, i mean that is Django framework all you need to create a web app or do you need to add it to the rest framework?. What is the connection between a web app and an API?. Does a web app need an API to function?. I'll appreciate a simple explanation of the difference between the two and and how they connect to each other. Thanks. -
Next Auth - OAUTH_GET_ACCESS_TOKEN_ERROR
I'm trying to implement oauth in my next.js app. for backend I'm using Django ODIC Provider and Next Auth for the front-end. but I'm getting an error: { "error": "invalid_grant", "error_description": "The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" } How can I fix this ? I have created a file named: [...nextauth].js in /api/auth/ and added my custom provider. Here's how my env looks like: NEXTAUTH_URL = http://localhost:3000 CLIENT_ID = 466647 CLIENT_SECRET = 079e7fe518e245cb316701faa19ec463c0073fba25d1e51c2db996ab SCOPES = openid profile email and [...nextauth].js: import NextAuth from 'next-auth' export default NextAuth({ providers: [ { id: "pullstream", name: "Pullstream", type: "oauth", version: "2.0", scope: process.env.SCOPES, params: { grant_type: "authorization_code" }, accessTokenUrl: "https://accounts.dev.pullstream.com/api/openid/token/", requestTokenUrl: "https://accounts.dev.pullstream.com/api/accounts/login/", authorizationUrl: "https://accounts.dev.pullstream.com/api/openid/authorize/", profileUrl: "https://accounts.dev.pullstream.com/api/accounts/profile/", async profile(profile, tokens) { console.log(profile, tokens) }, clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET } ], }) -
Scraping Bing or Google in Django
I am building a search engine for only men's apparel in django, so I need help in scraping Bing or Google and using custom querying to get only men's apparel results. body { font-size: 10pt; font-family: arial, sans-serif; } a { text-decoration: none; } a:hover { text-decoration: underline; } button { font-weight: bold; font-family: arial; } /* Top Toolbar */ .top-toolbar { height: 50px; } .top-toolbar nav { float:right; margin: 7px 21px; } .top-toolbar nav a { margin: 3px 6px; color: #404040; } .top-toolbar nav a:hover { color: #111111; } .top-toolbar nav button { padding: 7px 12px; border-radius: 2px; /* background-color: #4585F1;*/ background-image: -moz-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -o-linear-gradient(top left, #4084F9 0%, #4585F1 100%); background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, #4585F1), color-stop(1, #0097DE)); background-image: -webkit-linear-gradient(top left, #4084F9 0%, #4585F1 100%); color: white; border: 1px darkblue; font-size: 9.5pt; } .top-toolbar nav button:hover { box-shadow: 1px 1px 0 rgba(0,0,0,.2); } .top-toolbar nav img { margin: 0 7.5px; height: 22px; position: relative; top: 7px;} /* End of Top Toolbar */ /* Search */ .search { text-align: center; clear: both; margin: 11% 0 0 0; } .logo { max-width: 21%; margin: 0 auto; } .search img { margin-bottom: 3%; max-width: 100%; … -
How to model a database to a Dynamic HTML Form?
I'm trying to make a POST REQUEST to link Dynamic HTML form (when you push the add button, will add another textbox, like in the photo) into Django's default database. Right now I have the following issue, every time I submit data, it only saves the last row. How is the best way to model database and HTML form to save that data ? Any documentation is appreciate it ! Infraestructura.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action= "{% url 'infraestructura' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='Infraestructura' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> <!-- Submit buttom--> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> {% endblock %} models.py from django.db import models # Create your … -
Saving username to model in Django
I am creating a donation app that allows donors to create listings. This data is stored in a Django Model and is going to be displayed on a page. I want to save the user's username to the Django model and display it on the page. My code is down below Models.py class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) image = models.CharField(max_length=1000000) deliveryorpickup = models.CharField(max_length=8) description = models.TextField() Views.py from django.contrib.auth.models import User from django.http.request import RAISE_ERROR from django.http.response import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import forms, inlineformset_factory from django.contrib.auth.forms import UserCreationForm, UsernameField from .forms import CreateUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from home.models import Donation # Create your views here. def index(request,*args, **kwargs): return render(request, "index.html", {} ) @login_required(login_url='/login/') def dashboard(request,*args, **kwargs): return render(request, "dashboard.html", {} ) def register(request, ): if request.user.is_authenticated: return redirect('/dashboard/') else: form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('loginpage') context = {'form': form} return render(request, "register.html", context ) def loginpage(request): if request.user.is_authenticated: … -
Error starting django. server, because: ModuleNotFoundError: No module named 'djoser'
I can't run my server in django. When I attempt to start it with python3 manage.py runserver I recieve the error message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/kennethsutherland/Contractor_Project/contractorenv/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'djoser' I'm not sure what I'm doing wrong, becase djoser is in my installed apps in my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'accounts', 'social_django', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist' ] I've been looking at it, and can't figure out what's wrong. Would anyone have suggestions? -
I have removed a form from formset. now form submit not working on button click (Django)
I'm having a Formset which contains forms as Adventure Details, Adventure Pictures, and Adventure Pricing. Now I have removed Adventure Pricing form from formset, from formset.py file and frontend code also. Now while clicking on Update Adventure button, which is used for submitting formset and which was working earlier is now refreshes and loads the same page without updating anything. Please forgive this question rather than downvoting for not including any code -
Form doesn't display in template - Django
I try to create a form in Django's app but nothing display in browser. app.models.py from django.db import models class Scrap(models.Model): query = models.CharField(max_length=100) author = models.CharField(max_length=100) date = models.DateTimeField('date scrapped') h3 = models.TextField(max_length=500) links = models.TextField(max_length=10000) meta = models.TextField(max_length=10000) app.forms.py from django.forms import ModelForm from app.models import Scrap class ScrapForm(ModelForm): class Meta: model = Scrap fields = ['query',] app.views.py def get_query(request): if request.method == 'POST': form = ScrapForm(request.POST) if form.is_valid(): print('coucou') return redirect('/scrapping') else: form = ScrapForm() return render(request, "scrapping.html", {'form': form}) scrapping.html <form class="navbar-search form-inline mr-3 d-none d-md-flex ml-lg-auto post-form" action="" method="POST">{% csrf_token %} <div class="form-group mb-0"> <div class="input-group input-group-alternative"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-search"></i></span> </div> {{ form }} <input class="input-group-text" type="submit" value="OK" style="color:initial"> </div> </div> </form> When I inspect html page, form doesn't exist. Could you help me please ? -
Implementing Last Viewed functionality in Django
Am still a newbie but I want to implement "last viewed" functionality in my project and I want this functionality to be user specific. I want to show the users the last 10 objects that they viewed. how can I achieve this. I have seen similar problems with solutions but they are for single models, I want to do use multiple models here. Below is my models class Fblink(Link): class Meta: db_table = "Facebooklinks" get_latest_by = ['-watched_num', 'updated_at'] ordering = [F('user').asc(nulls_last=True)] verbose_name = "Fblink" verbose_name_plural = "Fblinks" class Twlink(Link): class Meta: db_table = "Twitterlinks" get_latest_by = ['-watched_num', 'updated_at'] ordering = [F('user').asc(nulls_last=True)] verbose_name = "TWlink" verbose_name_plural = "TWlinks" -
migrations folder have turned into .pyc files - can no longer run makemigrations
For some reason my migration-files now all are moved into the folder migratios/__pycache__ and turned into .pyc files. I have created a new model, and running python manage.py makemigrations returns No changes detected. Does the .pyc impact Django? How can I make my migration now? How do I stop this problem from happening again? -
how to use default django auth model in react , i want to access api that needs authentication in react?
currently i am using default django auth User model for authentication purposes like registering a new user, login a user and logout a user and now i want to access the authentication required API's in React so how to achienve that if that's not possible what should i do please briefly guide me , currently i am using Django Rest Framework my urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from authentication import views as authentication_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('liveclass_api.urls')), path('login/', auth_views.LoginView.as_view(template_name='authentication/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='authentication/logout.html'), name='logout'), path('register/', include('authentication.urls')), my login.html ** <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Login</legend> {{form}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info pt-3" type="submit">Login</button> </div> </form> <div class='border-top pt-3'> <small class='text-muted'> Want to get an account? <a class='ml-2' href={% url 'register' %}>Sign up now</a> </small> </div> </div> I am writing register or logput template as they are quite same, i want to modify this authentication or will have to use a new one to work with react Please help me in this process and apologies if not following the stackoverflow formatting guide as i am new to it Thanks -
ERR_BLOCKED_BY_CLIENT when I try to use geocodign api in js
I am trying to execute the following script (that is in moovit_script.js). I need to use reverse geocoding but I obtain an ERR_BLOCKED_BY_CLIENT in js console. lat, lng and status are ok, but destination address is ''. function set_moovitmap() { var m = document.getElementById('mapa_moovit'); const origin = window.opener.origin_ad; m.setAttribute("data-from-lat-long", window.opener.origin_coordinates); const lat = window.opener.latD; const lng = window.opener.lonD; const geocoder = new google.maps.Geocoder(); const latlng = { lat: parseFloat(lat), lng: parseFloat(lng), }; destination_address = ''; // window.alert(latlng.lat); geocoder.geocode({ location: latlng }, (results, status) => { if (status === "OK") { if (results[0]) { destination_address = results[0].formatted_address; } } }); window.alert(destination_address); m.setAttribute("data-from", origin); if (destination_address != '') { m.setAttribute("data-to", destination_address); } } I am using django and I have tried to execute this function in a html file: {% load static %} <script src="{% static 'moovit_script.js'%}"></script> <!-- <script src="{% static 'google_maps.js'%}"></script> --> <script src="https://maps.googleapis.com/maps/api/js?key=myKey&libraries=places"> </script> <div class="mv-wtp" id="mapa_moovit" data-to='' data-from='' data-from-lat-long='' data-lang="es"> <script> set_moovitmap(); </script> Thank you. -
NGINX redirects port 80, works well for other ports
My django runs on 127.0.0.0:8000 My nginx nginx conf is below worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location /{ proxy_pass http://127.0.0.1:8000/; } } } When I type localhost in browser, it redirects (url changes in the address bar) to 127.0.0.1:8000 instead of reverse proxying. when I listen on other ports such as 8001, it reverse proxies as expected Why it doesn't work as expected for listening on port 80?