Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Following ! ACCESS to my shope/models
Traceback (most recent call last): File "h:/Django Framwork/WebCard/Shope/views.py", line 3, in from .models import product ImportError: attempted relative import with no known parent package I cant Import or use product.objects and get access to product.objects.aLL() funcs i want to see my models of product shope/views.py from django.shortcuts import render from django.http import HttpResponse from .models import product product.objects.all() def Index(request): return render(request,'Shope/index.html') def about(request): return render(request,'Shope/about.html') def contant(request): return HttpResponse('This page is working') def tracker(request): return HttpResponse('This page is working') def search(request): return HttpResponse('This page is working') def productview(request): return HttpResponse('This page is working') def checkout(request): return HttpResponse('This page is working') # print(product.objects.all()) # m = django.apps.apps.get_models() # print(m)** Shope\Model.py from django.db import models import django.db # Create your models here. class product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) product_catagory = models.CharField(max_length=50) product_subcatagory = models.CharField(max_length=50) product_desc = models.CharField(max_length=300) product_pricse = models.IntegerField(max_length=50,default=0) product_pub_date = models.DateField() product_imag = models.ImageField(upload_to='shope/images') def __str__(self): return self.product_name # print(product.objects.all()) enter image description here -
local variable 'routingForm' referenced before assignment
Am trying to do a form submit,but getting the error"local variable 'routingForm' referenced before assignment".please help me to solve this. *****forms.py***** from django import forms class routingForm(forms.Form): areaDigit = forms.CharField(label='areaDigit', max_length=100) product = forms.CharField(label='product', max_length=100) *****views.py***** from django.shortcuts import render from .forms import routingForm # Create your views here. from django.http import HttpResponse,HttpResponseRedirect from .models import Product,Routing_Dest_Area def get_route_list(request): #areaDigit= request.POST.get('areaDigit', False) #data=Routing_Dest_Area.objects.filter(areaDigit_pk=request.POST['areaDigit']) if request.method == "POST": #Get the posted form routingForm = routingForm(request.POST) if routingForm.is_valid(): areaDigit = routingForm.cleaned_data['areaDigit'] else: MyLoginForm = routingForm() return render(request, 'routing/test.html',{'areaDigit':areaDigit}) *****home.html***** <form method="POST" action="{% url 'get_route_list'%}" id="routingForm" name="routingForm"> {% csrf_token %} <div class="form-content"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Area String *" name"areaDigit" id="areaDigit" value="{{areaDigit}}"/> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label for="sel1">Select list (select one):</label> <select class="form-control" id="Product" name="product"> <option> 1</option> <option> 21</option> </select> </div> </div> </div> <button type="submit" class="btnSubmit">Submit</button> -
Django - "warning" messages in class-based views not existing?
Im in Django and I'm trying to flash a "warning" message in a class-based view. But it seems like it's only possible to create "success" messages. The module django.contrib.messages.views only have the function SuccessMessageMixin, so there doesn't seem to be any equivalent to other types of messages. Been looking through the documentations but can't find any relevant info. -
Testing PUT method in Django Rest Framework
I'm trying to test a PUT method in django rest framework. I get HttpResponsePermanentRedirect instead of response object. My views for a put method are set to send status 200 after successful update. Error: self.assertEqual(response.data, serializer.data) AttributeError: 'HttpResponsePermanentRedirect' object has no attribute 'data' tests.py class PostTestGetAndPutMethod(APITestCase): def setup(self): Post.objects.create(title="POST CREATED", content="POST WAS CREATED") Post.objects.create(title="POST CREATED 2", content="POST WAS CREATED 2") Post.objects.create(title="POST CREATED 3", content="POST WAS CREATED 3") def test_get_posts(self): ''' Ensure we can get list of posts ''' # get API response response = self.client.get(reverse('posts')) # get data from DB posts = Post.objects.all() # convert it to JSON serializer = PostSerializer(posts, many=True) # check the status self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data) def test_update_put_post(self): ''' Check if we can update post ''' data = {'title': 'POST MODIFIED', 'content': 'CONTENT MODIFIED'} response = self.client.put('/posts/1', data) serializer = PostSerializer(data) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py @api_view(['GET', 'PUT', 'DELETE']) def post_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(post) return Response(data=serializer.data, status=status.HTTP_200_OK) elif request.method == 'PUT': serializer = PostSerializer(post, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': post.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
Django 'author' is not defined
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author - models.ForeignKey(User, on_delete = models.CASCADE) >>>NameError: name 'author' is not defined Why python does not recognize User paramether that is imported from django? GHOw can I fix that? -
is there any way can i use the Django for existing database? if yes how to used models?
I am working on already existing data on relational database. Now question is that how to build models and how to update the tables with new data coming from user (technically django forms)? -
Django getting session variables from a dictonary?
I don't know if this is even possible but can I get session objects from a dictonary in Django? e.g. somthing like this: def initial_view: ... else: request.session['send_something'] = {'sender', 'abc', '123', 'xyz'} return redirect('send_something_summary') def send_something_summary(request): send_something = request.session['send_something'] doing it like so always results in the following error: Object of type set is not JSON serializable Is there a way to do it somehow like that or do I have to set a new session object for each variable I want to pass to the next view like so: else: request.session['sender'] = 'sender' request.session['abc'] = 'abc' request.session['123'] = '123' request.session['xyz'] = 'xyz' Thanks for reading and kind regards -
WinError 10060 A connection attempt failed because the connected party did not properly respond after a period of time
1) add in settings.py ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'app.apps.AppConfig', ] ''' ''' ACCOUNT_ACTIVATION_DAYS=3 EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='xxxx@gmail.com' EMAIL_HOST_PASSWORD='xxxx' EMAIL_PORT=587 EMAIL_USE_TLS=True ''' 2) add url ''' urlpatterns=[ path('admin/',admin.site.urls), path('accounts/',include('registration.backends.default.urls')), ] ''' 3)migrate 4)update view.py add methos decorator for view where you want login required ''' from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required @method_decorator(login_required,name='dispatch') class StudentDetailView(DetailView): model = Student ''' [the singup page][1] [the error page][2] [1]: https://i.stack.imgur.com/yqizU.png [2]: https://i.stack.imgur. com/wROmM.png } -
Django Import error: cannot import "name"
I got an error i dont understand: cannot import name "UserUpdateForm" from "users.forms". Im doing the django tutorial from corey schafer, and we are creating a form as a class to update the users profiles of a blog page, then importing it to views.py and calling it in a function and when i try to run the server it pops up that error. I already looked for other questions but in general they say that the problem is a circular import, but i cant figure if it is my case and where it is. Im relatively new to programming so i dont really understand how this works, any help will be aprecciated: (Already tried to import the UserUpdateForm inside my profile function and didnt work) Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] class UserUptadeForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email"] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ["image"] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators … -
Why models.EmbeddedModelField is not working with djongo/django?
I have class Dimension and Feature. ( Want to create an Embedded Model from Feature to Dimension) Documentation: bottom of page I keep getting the error: dimension = models.EmbeddedModel AttributeError: module 'djongo.models' has no attribute 'EmbeddedModel' class Dimension(models.Model): dimensionName = models.CharField(max_length=20) def __str__(self): return self.dimensionName class Feature(models.Model): featureName = models.CharField(max_length=20) dimension = models.EmbeddedModel( model_container=Dimension, ) def __str__(self): return self.featureName Any leads would be appreciated! -
Problem with the index: create many links about the same
enter image description here I've tried several ways to try to solve the problem but still have the same error the idea is to go to the login page where you will have 2 types of authentication but in the home page it have a many bottons and one of these, its for to login can you help me? i need this finish as fast as possible above it contains the image of the print of what is happening #URLS.PY from django.contrib import admin from django.urls import include, path, re_path import posts.views urlpatterns = [ path('admin/', admin.site.urls), path('', include('PADEL_APP.directory_urls')), path('account/', include('allauth.urls')), path('', posts.views.test), ] LINKS HOME PAGE from django.contrib import admin from django.urls import include, path, re_path from django.views.generic import RedirectView from desktop.core_desktop import views urlpatterns = [ path('', views.index, name='index'), path('', RedirectView.as_view(url='index/all/', permanent=True)), path('about/', views.about, name='about'), path('about/', RedirectView.as_view(url='about/all/', permanent=True)), path('roules/', views.roules, name='roules'), path('roules/', RedirectView.as_view(url='roules/all/', permanent=True)), path('contacts/', views.contacts, name='contacts'), path('contacts/', RedirectView.as_view(url='contacts/all/', permanent=True)), path('privacy/', views.privacy, name='index'), path('privacy/', RedirectView.as_view(url='privacy/all/', permanent=True)), ] SETTINGS.PY import os import sys import json # Build paths inside the project like this: os.path.join(BASE_DIR, ...) from django.urls import reverse 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/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret … -
GraphQL multiple queries in one request in Django
Im using Django with graphene to build an API but i want to combine two models in one query, all the fields of the models are the same. Example schema.py import graphene from graphene_django import DjangoObjectType from .models import Post, Post2 class PostType(DjangoObjectType): class Meta: model = Post class Post2Type(DjangoObjectType): class Meta: model = Post2 class Query(graphene.ObjectType): post = graphene.List(PostType) post2 = graphene.List(Post2Type) def resolve_post(self, info): return Post.objects.all() def resolve_post2(self, info): return Post2.objects.all() I get this response: { "data": { "post": [ { "title": "post 1" } ], "post2": [ { "title": "post test" } ] } } What i want to get is: { "data": { "allPost": [ { "title": "post 1" }, { "title": "post test" } } } -
context processor: how to write login and signup in all views
I created a view for Login/Signup/Forget Password (5 forms in single view). I need these forms in header so I added links in base.html and extended in all templates. How can I make this view available for all templates. def master_link(request): login_form = UserLoginForm() send_otp_form = SendOTPForm() verify_otp_form = VerifyOTPForm() registration_form = RegistrationForm() forget_password_form = ForgetPasswordForm() if request.method == 'POST' and 'login_submit' in request.POST: login_form = UserLoginForm(request.POST) if login_form.is_valid(): user = login_form.login(request) if user: login(request, user) return HttpResponseRedirect(reverse('home')) elif request.method == 'POST' and 'send_otp_submit' in request.POST: send_otp_form = SendOTPForm(request.POST) if send_otp_form.is_valid(): mobile_number = send_otp_form.cleaned_data['mobile_number'] type_otp = send_otp_form.cleaned_data['type'] otp = random.randint(1000, 9999) otpobj = sendotp.sendotp.sendotp(settings.AUTH_KEY, str(otp) + ' keep otp with you.') otpobj.send(mobile_number, 'TestOTP', otp) return HttpResponseRedirect(reverse('verify_otp', args=(mobile_number, type_otp))) elif request.method == 'POST' and 'signup_submit' in request.POST: registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) mobile_number = registration_form.cleaned_data['mobile_number'] user.username = registration_form.cleaned_data['mobile_number'] password = registration_form.cleaned_data['password'] gender = request.POST.get('inlineRadioOptions') user.gender = gender user.mobile_number = mobile_number user.set_password(password) user.save() new_user = authenticate(username=mobile_number, password=password) login(request, new_user) return HttpResponseRedirect(reverse('home')) elif request.method == 'POST' and 'forget_password_submit' in request.POST: forget_password_form = ForgetPasswordForm(request.POST) if forget_password_form.is_valid(): password = forget_password_form.cleaned_data['password'] mobile_number = forget_password_form.cleaned_data['mobile_number'] user = User.objects.get(mobile_number=mobile_number) user.set_password(password) user.save() return HttpResponseRedirect(reverse('home')) elif request.method == 'POST': verify_otp_form = VerifyOTPForm(request.POST) if verify_otp_form.is_valid(): return HttpResponseRedirect(reverse('home')) # … -
docker-compose cannot wait for mysql database
I am having real problems trying to get a docker-compose script to initiate a mysql database and a Django project, but get the Django project to wait until the mysql database is ready. I have two files, a Dockerfile and a docker-compose.yml, which I have copied below. When I run the docker-compose.yml, and check the logs of the web container, it says that it cannot connect to the database mydb. However the second time that I run it (without clearing the containers and images) it connects properly and the Django app works. I have spent a whole day trying a number of things such as scripts, health checks etc, but I cannot get it to work. Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY ./ /code/ RUN pip install -r requirements.txt RUN python manage.py collectstatic --noinput docker-compose.yml version: '3' services: mydb: environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_USER=django - MYSQL_PASSWORD=secret - MYSQL_DATABASE=dbMarksWebsite image: mysql:5.7 ports: # Map default mysql port 3306 to 3308 on outside so that I can connect # to mysql using workbench localhost with port 3308 - "3308:3306" web: environment: - DJANGO_DEBUG=1 - DOCKER_PASSWORD=secret - DOCKER_USER=django - DOCKER_DB=dbMarksWebsite - DOCKER_HOST=mydb - DOCKER_PORT=3306 build: . command: … -
sqlite3 update conflict with django (Windows10) SQLite 3.8.3 or later is required (found 3.7.17))
I am using Windows 10 and installed django When I navigate into the folder where the manage.py file is an run python manage.py runserver I get the following output SQLite 3.8.3 or later is required (found 3.7.17)) I am using python 3.7.7 and the package for Sqlite installed is 3.31.1. Any ideas how to fix this? Tried to downgrade to django 2.1.2 via pycharm but did not work. -
Automatically attach to parent in nested API
I am trying to create a nested API with DRF with the following structure: projects/visits/activities/items/ projects can have multiple visits each visit has a number of activities each activity contains some items (images with metadata) I used NestedDefaultRouter and registered them after eachother: class NestedDefaultRouter(NestedRouterMixin, DefaultRouter): pass router = NestedDefaultRouter() projects_router = router.register('projects', ProjectViewSet) projects_router.register( 'visits', VisitViewSet, basename='projects-visit', parents_query_lookups=['project__code']).register('activities', AcivityViewSet, basename='projects-visits-activities', parents_query_lookups=['visit__project__code', 'visit__name'] ).register('items', ItemViewSet, basename='projects-visits-activities-items', parents_query_lookups=['item__project__code', 'item__visit__name','item__activity'] ) The goals is to get the following structure working: ENDPOINTS projects/ GET: list all projects projects/ POST: create new project projects// GET show project details projects//visits/ GET list all visits of a project projects//visits/ POST create a new visit projects//visits/ GET show visit details projects//visits/activities/ GET show all activities of certain visit of certain project projects//visits/activities/ POST create new activity of certain visit of certain project projects//visits/activities/ GET show visit details projects//visits/activities//items/ GET show all items of certain activity of certain visit of certain project projects//visits/activities//items/ POST create new item for certain activity projects//visits/activities//items/ GET show item details class Project(models.Model): name = models.CharField(max_length=100, null=True) code = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Visit(models.Model): project = models.ForeignKey(Project, related_name='visits',null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Activity(models.Model): activity = … -
How do I set up a django website with basic backend on Direct Admin?
I am new to website deployment. I have a website with basic backend functionality for sending emails in django. I have purchased a basic DirectAdmin Web Control panel for hosting my website. I was able to set it up for static files of HTML by just simply uploading the files. But how do I go about for dynamic websites, i.e with backend functionality? Do I have to set up an Apache server or so and where do I configure the settings? The Direct Admin dashboard shows options in the GUI such as Apache handlers, MyPHP Admin etc but I am lacking the understanding on how to utilise these features. How do I possibly set up the servers and install the requirements and get it running? Please point me towards good resources for the same as I am absolutely lost. -
Django Making a Dynamic Form
I have a model called forms which can be edited from the admin panel with a list of fields lets say text1, text2, text3, image1, image2, image3. The admin can do in and input values for those lets say text1='First Name', text2='Last Name', text3='Email', image1='Logo', image2='', image3=''. Then I have another model named automation with fields the same fields but the values are what it corresponds to (so in the Form model they are all CharField but in Automation model they have the corresponding field CharField, ImageField, FileField, etc). The goal is to render a form that only displays the fields that actually have a value in Form and that value is the label for the form. So for the example above you would get a form like so: First Name: Last Name: Email: Logo: And the image 2 and image 3 are not rendered because there is no value for those in the Form model. I was able to get this working with the code below: forms.py file def get_automation_form(data): class AutomationForm(forms.ModelForm): class Meta: model = Automation fields = data[0] labels = data[1] return AutomationForm views.py file @login_required def form(request): if request.method == 'GET': nickname = request.GET.get('nickname') elif request.method … -
if statement is not working, it is automatically using else statement
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User, auth def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] user = User.objects.create_user(username=username, password=password1,email=email,first_name=first_name,last_name=last_name) user.save() return render(request, 'register.html') else: return HttpResponse('run') -
Is it possible in Django model to update a manually created primary key field using a calculated value during save()
IMPORTANT: NOT FOR Dorks. Dorks please excuse and leave this question alone. Now the question: Is it possible in Django to update the manually created primary key field of a model with a predetermined / calculated value during save()? In the following model, for example: class Port_Berthing(models.Model): doc_number = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_on = models.DateField(default=timezone.now, verbose_name='Created on') effective_date = models.DateField(verbose_name='Effective From') berthing_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last doc_number value, increment it by 1 and insert the calculated value in the primary key field doc_number for the new record. And if it is possible, can we do this in the model's save() method? -
Dynamic File Paths with Django 3.x and Graph API
I am complete noob to django and using api's. In the process of doing some research I need to look through a bunch of files to extract some meta data. Originally I planned to copy the data down from onedrive and go through the hassle of deploying a server to expose the data. However the data is currently stored on onedrive, and thought it would be easier to access it with a web app/ console application. I went through the process of creating the sample django/python sample application and am able to run that, and figured out the correct permissions to access the root directory, but am stuck on how to go from that to being able to traverse folders and read/download the interesting files. The option I would like at the moment would be to have employ a file navigation. I saw another example from a long time ago with django, but I am having a hard time following it. Ideally I could make a request to the root drive, get the children and render a page with the list of files and folders with url links to the folder contents. clicking the file would render the meta data … -
Matching id's for different models
I have two models. First one creates a work order, second one creates en entry for it. But when i try to access this entry i get NoReverseMatch error. I know this has something to do with id's being generated on random and not matching each other, but i can't figure out how to solve this (i'm new to coding). here's my urls # Home page re_path(r'^$', views.index, name='index'), # Maintenance page re_path(r'^maint/$', views.maint, name='maint'), # Show all open work orders re_path(r'^maint/orders/$', views.orders, name='orders'), # Show all open work orders re_path(r'^maint/closed_orders/$', views.closed_orders, name='closed_orders'), # Detail page for a single work order re_path(r'^maint/orders/(?P<order_id>\d+)/$', views.order, name='order'), # Page for adding new work orders re_path(r'^new_order/$', views.new_order, name='new_order'), # Page for adding a new entry re_path(r'^new_entry/(?P<order_id>\d+)/$', views.new_entry, name='new_entry'), # Page for editing an entry re_path(r'^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), models class Order(models.Model): """Maintenance work orders""" date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User,on_delete=models.CASCADE) entry_filled = models.BooleanField(default=False) repair_filled = models.BooleanField(default=False) closed = models.BooleanField(default=False) def __str__(self): """return a string representation of the model.""" return str(self.id) class Entry(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) origin = models.CharField(max_length=20) local = models.CharField(max_length=200) descr = models.TextField() date_added = models.DateField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): return str(self.descr)[:50] +"..." view def edit_entry(request, entry_id): """Edit an existing entry.""" … -
How to delete comment
I'm a Django beginner, how do I delete comment from blocked user. For example if user A blocked user B, I want all the comment in user 'A post in B post' and 'B post in A post' to be deleted. The issue about my code is that when user A block user B, all the comment from user A is deleted from user B post, and also user A comment is deleted from A post, that is not what I want. I want user A comment deleted from user B post and user B comment deleted from user A post. -
Django Oracle cursor call external database view
I established a connection from my Django's project to external a Oracle database, connection it's done successfully and I can call store procedures or functions correctly like this: days = cursor.callfunc('VAC_DICT', cx_Oracle.NUMBER, (identification,)) result = cursor.callproc('PINS_VAC', [data.get('identification'),'true']) Thing is, I need to call a database view there called 'VAC_HIST', but when I try it this way: periods = cursor.execute('VAC_HIST') It gets me "django.db.utils.DatabaseError: ORA-00900: invalid SQL statement", got it, make sense that Im not using the correct syntax, but I searched a lot and can't find how to use cursor. something to call views, like "cursor.callview" or other.... Any idea how or what am I missing ?, thanks in advance. -
How to return query set in SerializerMethodField in Django
if I have SerializerMethodField and I wants to return query set. I tried to do this but doesn’t work available_times = serializers.SerializerMethodField() def get_available_times(self, obj): qs = AvailableTimes.objects.filter(hall__id=obj.id) serializer = AvailableTimesSerializer(qs, read_only=True ,many=True) return serializer.data it not working... give and Error.