Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Resf Framework: auto fill a field of a Model when POST?
Is there a way of filling some particular fields in a model using a field value of another model object? For example, I thought of the following scenario: 1 - there are some models from django.db import models class Supplier(models.Model): supplier = models.Charfield(max_length=50, unique=True) class Object(models.Model): object = models.Charfield(max_length=50) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, to_field="supplier") class Transaction(models.Model): object_id = models.ForeignKey(Object, on_delete=models.CASCADE) supplier = models.Charfield(max_length=50) 2 - Those models are serialized from . import models from rest_framework.serializers import ModelSerializer class SupplierSerializer(ModelSerializer): class Meta: model = models.Supplier fields = '__all__' class ObjectSerializer(ModelSerializer): class Meta: model = models.Object fields = '__all__' class TransactionSerializer(ModelSerializer): class Meta: model = models.Transaction exclude = ('supplier',) 3 - And there is a view from . import models, serializers from rest_framework.viewsets import ModelViewSet class TransactionApiViewset(ModelViewSet): queryset = models.Transaction.objects.all() serializer_class = serializers.TransactionSerializer When submiting a post with 'object_id' field to Transaction Api, I'd like that the 'supplier' field in Transaction Model autofills with the 'supplier' field value of Object object related to 'object_id'. I'd appreciate any help. -
Many-to-many relationships | adding objects
I have two moedls, Factures and Réglements In template i have a list of factures objects with checkbox next to every one using this method i want to add a Réglements for the checked objects Views: def Ajout_Réglement_Vente(request): if request.method == "POST": N_Réglement = request.POST["Numéro_Réglement"] Date_Réglement = request.POST["Date_Réglement"] réglement = Réglements(N_Réglement=N_Réglement, Date_Réglement= Date_Réglement) réglement.save() if not request.POST.get('Action', None) == None: m = request.POST.getlist('Action') for i in m: f = Factures.objects.get(pk=i) f.Type_Facture = 'Facture Vente Réglé' f.save() Models: class Réglements(models.Model): N_Réglement=models.CharField( max_length=50, default='null') Date_Réglement=models.DateField(auto_now_add=False, auto_now=False,blank=True, null=False) Mode_Réglement=models.CharField(max_length=50, default='null') Montant= models.CharField(max_length=50, default='null') N_Pièce = models.CharField(max_length=50, default='null') Factures = models.ManyToManyField(Factures) def __str__(self): return self.N_Réglement class Factures(models.Model): N_Facture=models.CharField( max_length=50, default='null') Date_Facture=models.DateField(auto_now_add=False, auto_now=False,blank=True, null=False) Valeur= models.CharField(max_length=50, default='null') Type_Facture = models.CharField(max_length=50, default="Facture Achat") def __str__(self): return self.N_Facture -
Even after having the account_account I am facing the error "django.db.utils.ProgrammingError: relation "account_account" does not exist"
I am trying to create a API with OAuth 2 Authentication. I have created custom user models called Accounts. When I am running the command "py manage.py migrate" it is throwing me the below error. E:\Django\api\app>py manage.py migrate Operations to perform: Apply all migrations: account, admin, app_v2, auth, contenttypes, oauth2_provider, sessions, social_django Running migrations: Applying oauth2_provider.0001_initial...Traceback (most recent call last): File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "account_account" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\Django\api\app\manage.py", line 22, in <module> main() File "E:\Django\api\app\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 230, in apply_migration migration_recorded = True File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 118, in __exit__ self.execute(sql) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line … -
Django CRUD :Update function is not working
I made CRUD in django. Update is not working while creating and deleting views are working.Pleas fix my problem.And tell me where i am lacking. This is views.py: ` from .import models from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render from .forms import readerRegistrationForm from .models import Reader, books from django.views.generic import TemplateView,RedirectView,UpdateView from django.views import View # Create your views here. def done(request): return render(request,'done.html') class addshowView(TemplateView): template_name='add&show.html' def get_context_data(self,*args,**kwargs): context= super().get_context_data(**kwargs) fm=readerRegistrationForm() stu=Reader.objects.all() cone=books.objects.all() context={'str':stu,'form':fm,'con':cone} return context def post(self,request): fm=readerRegistrationForm(request.POST) if fm.is_valid(): fm.save() return HttpResponseRedirect('/') class userdeleteview(RedirectView): url='/' def get_redirect_url(self, *args, **kwargs): p=kwargs['id'] Reader.objects.get(pk=p).delete() return super().get_redirect_url(*args, **kwargs) class Updateview(UpdateView): def get(self,request,id): pi=Reader.objects.get(pk=id) fm=readerRegistrationForm(instance=pi) return render(request,'updateit.html',{'form':fm}) def post(self,request,id): pi=Reader.objects.get(pk=id) fm=readerRegistrationForm(request.POST,instance=pi) if fm.is_valid(): fm.save() return render(request,'updateit.html',{'form':fm})` This is forms.py ''' from django.forms import fields, widgets from .models import books,Reader class readerRegistrationForm(forms.ModelForm): class Meta: model=Reader fields=['name','email','comment'] 'this is models.py' from django.db.models.deletion import CASCADE #Create your models here. class books(models.Model): name=models.CharField(max_length=200) gener=models.CharField(max_length=200) author=models.CharField(max_length=200) isbn=models.BigIntegerField() def __str__(self) : return self.name class Reader(models.Model): name=models.CharField(max_length=200) email=models.EmailField(max_length=200) comment=models.TextField() def __str__(self) : return self.comment ''' This is urls.py ''' from django.contrib import admin from django.urls import path from boom import views urlpatterns = [ path('', views.addshowView.as_view() , name='show'), path('updated/',views.done,name='done'), path('delete/<int:id>/', views.userdeleteview.as_view() , name='doNow'), path('update/<int:id>/', views.Updateview.as_view() , name='UpNow'), … -
How to run Django channels with StreamingHttpResponse in ASGI
I have a simple app that streams images using open cv and the server set in wsgi. But whenever I introduce Django channels to the picture and change from WSGI to ASGI the streaming stops. How can I stream images from cv2 and in the same time use Django channels? Thanks you in advance My code for streaming: def camera_feed(request): stream = CameraStream() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') settings.py: ASGI_APPLICATION = 'photon.asgi.application' asgi.py application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) -
Django - Authentication not functioning in when deployed
I am unable to log in after deploying my Django application, but can when using the inbuilt dev server. I'll put the error and what im using below. I have migrated to the live sql server with no errors. I created a superuser with no errors. the only real change to the django files was getting static files set up which shouldnt impact the db (where im assuming this error is coming from). Here is the error: TypeError at /login/ argument of type 'NoneType' is not iterable Request Method: POST Request URL: http://sitename/login/ Django Version: 3.0 Exception Type: TypeError Exception Value: argument of type 'NoneType' is not iterable Exception Location: c:\python39\lib\site-packages\sql_server\pyodbc\base.py in encode_value, line 59 Python Executable: c:\python39\python.exe Python Version: 3.9.4 Now a few core notes about whats running in the environment and how its deployed: deployed on windows IIS utilizing mssql with django_mssql_backend-2.8.1 (ive verified all packages are on the same version. I think the only difference is python on 3.9.1 in dev vs 3.9.4 in prod) Django 3.0 SQL Server is on 2019 in dev vs 2017 in prod. not sure if that changes anything or i need to change any settings due to this but the inital … -
Can we deploy Two stand alone projects On Production Level and connect it together
My Social Media Team want to use NodeJs(for backend) and ReactJs(for frontend). and my other team want to use Django(for backend) and ReactJs(Frontend). My Question is Can We connect these two Program together on the production level and make it a single project at time of deployment? -
All values go into one column in a table in Django. How to separate?
I would like to create a table as an output, like in the picture below. views.py: test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total') Desired outcome: What I has tried: Can you please help me why all goes under the Currency, and not into the Number of coins column? -
I have a problem in POST method in python
I am using windows(10) and django library I wanted to make sign up option in my e-commerce so I made an app called accounts, I wrote in its models from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) print('In Post') else: form = UserCreationForm() context = {'form' : form} return render(request , 'registration/signup.html' , context) And I wrote in my signup.html page {% extends "base.html" %} {% block body %} <main class="mt-5"> <div class="container mynav"> <form action="" method="post"> {% csrf_token %} {{form}} <button type="submit" class="btn btn-primary">Sign up</button> </form> </div> </main> {% endblock body %} The problem in the POST method when I tried to run it he said The view accounts.views.signup didn't return an HttpResponse object. It returned None instead. What do I write to solve this problem? And Thanks. -
Django object cache with memcache after pickling
I was trying to cache a Django model Instance like class MyModel(models.Model): ... several atributes, as well as foreign key attributes ... from pymemcache.client import base import pickle obj = MyModel.objects.first() client = base.Client(("my-cache.pnpnqe.0001.usw2.cache.amazonaws.com", 11211)) client.set("my-key", pickle.dumps(obj), 1000) # 1000 seconds # and to access I use obj = pickle.loads(client.get("my-key")) They both works fine, but sometimes executing the same line: client.get("my-key") generates very very strange errors.(different errors like KeyError, OSError) like Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 791, in _extract_value key = remapped_keys[key] KeyError: b'some-other-cache-key' and sometimes I get: Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 833, in _fetch_cmd raise MemcacheUnknownError(line[:32]) and sometimes, I get Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 790, in _extract_value buf, value = _readvalue(self.sock, buf, int(size)) File … -
Django: is there an assertNumQueries method which can run the assertion as a subtest?
I'd like to run a block of code and ensure the amount of queries generated is in check, however, I want the test code to proceed if this check fails. Pseudo-code: def assertNumQueriesSubTest(func, expected_number): with self.countNumQueries as query_count: func() with self.subTest('query check'): self.assertEqual(queries_count, expected_number) With the classic assertNumQueries, the test code stops if the query count does not match the expected value, however, this prevents me from debugging tests properly, since the reason for which the query count changed may not be obvious, so I would like to know if at least the behavior matches is still the same or not. -
NoRevereMatch for named URL with keyword arguments
Error shown: Reverse for 'post_detail' with keyword arguments '{'username': 'admin', 'group_name':'laravel', 'pk': ''}' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/groups/(?P<group_name>[-a-zA-Z0-9_]+)/posts/(?P<pk>[0-9]+)/general/$'] group_list.html This is a generic ListView template. ... {% for group in object_list %} {% with group.post_set.all|first as post %} <a href="{% url 'post_detail' username=user.username group_name=group.name_slug pk=post.pk %}">{{ group.name }}</a> {% endwith %} {% endfor %} ... Main issue: In the template file, all three of the arguments are displayed correctly i.e. {{ user.username }} {{ group.name_slug }} {{ post.pk }}. But, if they are passed in as keyword argument in the named URL, one of the three is empty, and other two correctly passed. Note: There is no space between individual URL keyword arguments. -
django form not working when manually rendering form fields
I have a django form that I was rendering with {{ form | crispy}} for front end purposes I need to render the form fields manually. When rendering the fields manually the form does not submit. It works perfectly if I use the {{ form | crispy}}. The only change i made to the code is in the html rendering the elements manually html <div class="content-section"> <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form.image | as_crispy_field}} <h4>heading text</h4> <hr class="solid"> {{ form.title | as_crispy_field}} <h4>Heading text</h4> <hr class="solid"> {{ form.model | as_crispy_field}} <h4>Heading text</h4> <hr class="solid"> {{ form.manufacture | as_crispy_field}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(Post,self).save(*args, **kwargs) forms.py from crispy_forms.layout import Fieldset, Layout from django.forms import ModelForm from blog.models import Post, Manufactures, Models from crispy_forms.helper import FormHelper class PostForm(ModelForm): class Meta: model = Post fields = 'image', 'title', 'model', 'manufacture' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() if 'manufacture' in self.data: try: model_manufacture_id = int(self.data.get('manufacture')) self.fields['model'].queryset = Models.objects.filter(model_manufacture_id=model_manufacture_id)#.order_by('name') except (ValueError, … -
Redirect user to different page after successful login attempt
I'm making a simple CRUD app and learning how to handle making user accounts and logging in. When a user successfully logs in, I'd like him to be redirected to a certain page (for example, BASE_URL + '/notebooks'). What would be the best way to go about this? I'm stumped as to how exactly to go about this. I was thinking of using react-router-dom's useHistory() hook and just doing history.push() on the handleSubmit function, but then how would I return the response data to the form? Should I try to go about this using the backend? Here's my login form: export function Login() { const [ email, setEmail ] = useState('') const [ password, setPassword ] = useState('') async function handleSubmit(e) { e.preventDefault() try { const response = await axiosInstance.post( '/auth/token/obtain/', { email, password } ) axiosInstance.defaults.headers['Authorization'] = 'JWT ' + response.data.access localStorage.setItem('access_token', response.data.access) localStorage.setItem('refresh_token', response.data.refresh) return response.data; } catch(err) { throw err; } } return ( <div> <div> <div> <div> <div> <p> Log in </p> </div> <div> <form onSubmit={handleSubmit}> <ol> <li> <input name='email' value={email} placeholder='Email address' onChange={e => setEmail(e.target.value)} /> </li> <li> <input name='password' type='password' value={password} placeholder='Password' onChange={e => setPassword(e.target.value)} /> </li> <li> <input type='submit' value='Submit' /> </li> </ol> … -
Django log login attemps and after 3 failed attemps lock out user
So i am pretty new to Django. Actually my first project. I want to create a custom model "Logging" in which i want to log the admin login attempts and count the attempts. After 3 failed login attempts the user must me locked out. So how can i log custom admin attempts? -
some CSS is not working after adding "extends/base,html"
I am building a toggle button and i am using some CSS but when i try to run code then one CSS command is not working. When i remove {% extends 'base.html' %} then it works perfectly but after adding it doesn't load a function. toggle.html .menu-item, .menu-open-button { background: #EEEEEE; border-radius: 100%; width: 80px; height: 80px; margin-left: -35px; margin-top: 230px; position: absolute; color: #FFFFFF; text-align: center; line-height: 100px; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); -webkit-transition: -webkit-transform ease-out 200ms; transition: -webkit-transform ease-out 200ms; transition: transform ease-out 200ms; transition: transform ease-out 200ms, -webkit-transform ease-out 200ms; } line-height: 100px; is not working after adding extends base.html which is necessary. I have searched everywhere AND i have also tried by deleting every element on base.html then i notice that after deleting every single link it is working. Any help would be much Appreciated. Thank You in Advance. -
Is there a better solution instead of ModelMultipleChoiceField?
I have a form where users can create a fishing trip and they can add multiple participants from the registered users (fishermen). models.py class Fisherman(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fisherman_id = models.AutoField(primary_key=True) class Meta: verbose_name = "Fisherman" verbose_name_plural = "Fishermen" def __str__(self): return f'{self.user.username}' class Trips(models.Model): lake = models.CharField("Lake", max_length=150) city = models.CharField("City", max_length=100, blank=True) s_date = models.DateTimeField("Starting Date", auto_now=False, auto_now_add=False) e_date = models.DateTimeField("Ending Date", auto_now=False, auto_now_add=False) fisherman = models.ManyToManyField(Fisherman) trip_id = models.AutoField(primary_key=True) total_catch_weight = models.DecimalField(max_digits=5, decimal_places=2, default=0) class Meta: verbose_name = "Trip" verbose_name_plural = "Trips" def __str__(self): return f"{self.lake} - {self.trip_id}" forms.py class TripsForm(forms.ModelForm): fisherman = forms.ModelMultipleChoiceField(queryset=Fisherman.objects.all().exclude(user__username="admin"), widget=forms.SelectMultiple(attrs={'class': 'form-select'})) class Meta: model = Trips fields = ["lake", "city", "s_date", "e_date", "fisherman"] widgets = { "lake": forms.TextInput(attrs={'type': 'text', 'class': 'form-control', 'id': 'LakeInput',}), "city": forms.TextInput(attrs={'type': 'text', 'class': 'form-control', 'id': 'CityInput',}), "s_date": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control', 'id': 'StartingDate',}), "e_date": forms.DateTimeInput(format='%Y-%m-%d %H:%M', attrs={'class':'datetimefield form-control', 'id': 'EndingDate',}), } I'm currently using ModelMultipleChoiceField that lists all existing fishermen in the form, but I would like to find a better solution because I don't want that users could see all registered fishermen. Is there a way to add more fishermen to the trip by typing their names? Is it possible in case of manytomanyfield? I don't … -
how to show Html Div after Ajax Success in Django
i have Djnago App and i want message appear to the user after Ajax call Successs here is y Messages html <a id="added" class="btn btn-template-outlined" href="{% url 'shop:add_product' id=products.id %}">Add to cart</a> <p id="connt" class="text-center"> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </p> and here is my Ajax $("#added").click(function(e){ e.preventDefault(); $.ajax({url: "{% url 'shop:add_product' id=products.id %}", success: function(response){ appendToUsrTable(); }}); }); function appendToUsrTable() { ("#connt").append(` `) } </script> -
While Running GraphQL mutaion I am constantly getting this error
#unknown argument on field of type mutation #simple query I am running even after changing the input name it is throwing syntax error Can you please suggest mutation { createUnapprovedPart(Input:{part:"1234"}) { part {id} changeset { id creationDate effectiveDate } } If I change the name I am getting like syntax error -
Confusion about django
I am new to web development. I have already learned basic HTML, CSS and javascript. I want to use django as a backend. And I am aware of frontend framework like REACT. I want to use mongo db database and REACT framework along with Django. Can I do so or not. I mean can i integerate all these things to make a web application and if so what are advantages or disadvantages or should I go for MERN. -
How i can compare string if it has both quotation marks and apostrophes?
I want to check in my x.html file if value of string string has specific text - this text is aaaa"'b' and 'c'"aaaa So it has both, quotation marks and apostrophe. In this case when i do this {% if string == "aaaa"'b' and 'c'"aaaa" %} do something {% endif %} this is not working. How i can cope with that? -
Cannot assign "2": "Card.set" must be a "Set" instance
I am currently making a flashcard web application with Django. There is a 'set' page (dashboard) and a 'card' page (set-edit). When I fill in and submit the form on the card page (set-edit) to add a new card to the set which has been selected for editing, I receive a value error 'Cannot assign "2": "Card.set" must be a "Set" instance.' I'm unsure why this is happening because there is an instance of Set with an id of 2. Any suggestions of how to rectify this issue? views.py ################### ##Dashboard views## ################### def dashboard(request): set = Set.objects.all() set_count = set.count() if request.method == 'POST': form = SetForm(request.POST) if form.is_valid(): form.save() set_name = form.cleaned_data.get('name') messages.success(request, f'{set_name} has been added') return redirect('dashboard-dashboard') else: form = SetForm() context = { 'set': set, 'form': form, } return render(request, 'dashboard/dashboard.html', context) ############# ##Set views## ############# #Cards is for when you are adding cards to a set or looking at the content of a set def set_edit(request, pk): set_title = Set.objects.get(id=pk) card = Set.objects.get(id=pk).card_set.all() set_id = pk set = Set.objects.get(id=pk) if request.method == 'POST': form = CardForm(request.POST) print('Entered Post condition') if form.is_valid(): obj = form.save(commit=False) obj.set = pk obj.save() card_name = form.cleaned_data.get('kanji') messages.success(request, f'{card_name} has … -
I am working on DjangoRest project whenever i try to execute command python manage.py runserver or python manage.py shell It won't work
This is my settings.py file and I've created a .env file which contains secret key and other stuffs. I tried installing reinstalling python changing path deleting and again adding project and even I reinstalled vs code but it won't work i dont know where's the problem. This command python manage.py runserver or python manage.py shell or any other related commmand won't work """Settings.py""" """ Django settings for doorstepdelhi project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from decouple import config import django_heroku import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ["localhost", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', "versatileimagefield", "nested_admin", 'drf_yasg', "django_extensions", 'channels', "accounts", "webtraffic", "store", "product", "shop", "wishlist", "payment", 'core', … -
Login with google
Several social services will not allow redirecting users to 127.0.0.1 or localhost after a successful authentication; they expect a domain name. In order to make social authentication work, you will need a domain. ............................................................................................. If you are using Windows, your hosts file is located at C:\Windows\System32\Drivers\etc\hosts. To fix this edit your /etc/hosts file and add the following line to it: 127.0.0.1 mysite.com .............................................................................................. So, the problem is that it returns "mysite.com refused to connect." -
How do I have child divs automatically position restrained within a parent div?
I have the following CSS for a div box within a larger page container div: .mybox{ position: relative; width:20%; max-height: 100%; min-height: 25%; } I want to be able to add multiple of these dynamically using a django for loop, so I want them to space themselves out automatically while still remaining inside the parent div. This is because I can't set position values on each item if they are created at runtime. Anyone know how I can do this?