Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inherit from one class in Models.py into another class and turn it into a dropdown in Django
I have different classes in models.py that define an item's details. I need to make a new class that uses details listed in the existing classes and turn that into drop down menu (choices). How would I inherit from those other classes and turn it into a drop down? I am fairly new to python and django, I was thrown into the deep end and I'm trying to figure things out as I go, I'm not even sure where to start with this issue. Here is one of the classes: class StockItem(models.Model): item_id = models.AutoField(primary_key=True) stock_code = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self) return self.description Here is the class that needs to inherit from the above class: class StockInventory(models.Model): serial_number = models.CharField(max_length=255) stock_item = # needs to get the description from StockItem class above # and have its contents as a drop down stock_item in StockInventory needs to get what the user typed into description under StockItem and have it shown as a drop down with all descriptions previously entered. As I said, I am fairly new to this (been doing it for a month with no prior coding experience), so I apologize if I am asking something very stupid. -
Django Cookie-Cutter with Docker "python: can't open file 'manage.py': [Errno 2] No such file or directory" Error Macbook
I am trying to setup Django Project using Cookie-cutter with Docker using this tutorial: https://realpython.com/development-and-deployment-of-cookiecutter-django-via-docker/. I followed the instructions step by step, and I was able to successfully run all commands until the step when I need to run: docker-compose -f local.yml run django python manage.py makemigrations. This command gives me an error: python: can't open file 'manage.py': [Errno 2] No such file or directory . I've searched around online for the problem, the problem seems to be that the source files of the Django project is not copied inside the app directory of the docker. I tried running these commands to check if the files were there: docker-compose -f local.yml run django sh ls -la And indeed, the files weren't there, specially manage.py. Why is that so? Here's a screenshot: -
Django get all rows of models identified by foreign key
The European privacy policy requires to give information which data a website has about a user. With Django 1.11. I can get all relations to a specific user by ._meta.get_fields. Is there a nice way to iterate over the relations and get the actual data as rows? This is what my relations look like: In [1]: from test_project.people.models import Profile ...: user = Profile.objects.get(id=1000) ...: user._meta.get_fields(include_hidden=True) ...: Out[1]: (<ManyToOneRel: admin.logentry>, <ManyToOneRel: avatar.avatar>, <ManyToOneRel: dialogos.comment>, <ManyToOneRel: agon_ratings.rating>, <ManyToOneRel: announcements.announcement>, <ManyToOneRel: announcements.dismissal>, <ManyToOneRel: actstream.follow>, <ManyToManyRel: user_messages.thread>, <ManyToManyRel: user_messages.thread>, <ManyToOneRel: user_messages.groupmemberthread>, <ManyToOneRel: user_messages.userthread>, <ManyToOneRel: user_messages.message>, <OneToOneRel: tastypie.apikey>, <ManyToOneRel: guardian.userobjectpermission>, <ManyToOneRel: oauth2_provider.application>, <ManyToOneRel: oauth2_provider.grant>, <ManyToOneRel: oauth2_provider.accesstoken>, <ManyToOneRel: oauth2_provider.refreshtoken>, <ManyToOneRel: oauth2_provider.idtoken>, <ManyToOneRel: invitations.invitation>, <ManyToOneRel: account.emailaddress>, <ManyToOneRel: socialaccount.socialaccount>, <ManyToOneRel: base.contactrole>, <ManyToOneRel: base.resourcebase>, <ManyToManyRel: base.resourcebase>, <ManyToOneRel: layers.uploadsession>, <ManyToOneRel: maps.mapsnapshot>, <ManyToOneRel: people.profile_groups>, <ManyToOneRel: people.profile_user_permissions>, <ManyToOneRel: groups.groupmember>, <ManyToManyRel: services.service>, <ManyToOneRel: services.serviceprofilerole>, <ManyToOneRel: upload.upload>, <ManyToOneRel: favorite.favorite>, <ManyToOneRel: monitoring.notificationreceiver>, <ManyToOneRel: mapster_adapter.mapstoreresource>, <ManyToOneRel: pinax_notifications.noticesetting>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: password>, <django.db.models.fields.DateTimeField: last_login>, <django.db.models.fields.BooleanField: is_superuser>, <django.db.models.fields.CharField: username>, <django.db.models.fields.CharField: first_name>, <django.db.models.fields.CharField: last_name>, <django.db.models.fields.EmailField: email>, <django.db.models.fields.BooleanField: is_staff>, <django.db.models.fields.BooleanField: is_active>, <django.db.models.fields.DateTimeField: date_joined>, <django.db.models.fields.CharField: organization>, <django.db.models.fields.TextField: profile>, <django.db.models.fields.CharField: position>, <django.db.models.fields.CharField: voice>, <django.db.models.fields.CharField: fax>, <django.db.models.fields.CharField: delivery>, <django.db.models.fields.CharField: city>, <django.db.models.fields.CharField: area>, <django.db.models.fields.CharField: zipcode>, <django.db.models.fields.CharField: country>, <django.db.models.fields.CharField: language>, <django.db.models.fields.CharField: timezone>, <django.db.models.fields.related.ManyToManyField: groups>, <django.db.models.fields.related.ManyToManyField: user_permissions>, <taggit.managers.TaggableManager: keywords>, <django.contrib.contenttypes.fields.GenericRelation: tagged_items>, <django.contrib.contenttypes.fields.GenericRelation: actor_actions>, <django.contrib.contenttypes.fields.GenericRelation: target_actions>, … -
Can I include complete Python scripts from GitHub to a Django application?
I have a question before I get started in a whole project... I'm in a team of 6 people, and I'm the only one using Python. I only use scripts already written, I just put in the arguments and that's it (scripts like Sherlock : https://github.com/sherlock-project/sherlock or Twint : https://github.com/twintproject/twint By the time, I learned a bit about coding in Python but really, it remains basic stuff. Now, my colleagues would like to use these applications too, and I thought about using Django, set up a web server, importing those scripts in the server, and giving the possibility to my colleagues to enter the args in a user-friendly way (some really don't know a thing about programmation) Is that possible with Django? If yes, will it be complicated? (I never used Django before and will follow courses, don't have a deadline) If no, do you guys know of any alternatives that I could use? Thanks for your answers! -
How to make a view that records the data from a ModelMultipleChoiceField form in database with django?
I use a ModelMultipleChoiceField form in my website, because it helps me check the presence of users (employees) at work or not. But I don't understand how can I recover the data from my form to write them in my model (database). form.py : class HoursDeclarationForm(forms.Form): number_of_hours = forms.FloatField(required=True) presense = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple ) views.py : from django.contrib.auth.models import User from registration.models import UserExtention def hours_declaration (request): form = HoursDeclarationForm(request.POST or None) if form.is_valid(): number_of_hours = form.cleaned_data['number_of_hours'] presence = form.cleaned_data['presence'] for user in presence : #this is the part I can not achieve return render ( request, 'HoursDeclaration/hours_declaration.html' , locals() ) models.py : class UserExtention (models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, verbose_name='utilisateur') town = models.CharField (max_length=50, null=True, blank=True, verbose_name='ville') address = models.CharField (max_length=500, null=True, blank=True, verbose_name='adresse') hours_number = models.IntegerField (null=True, blank=True, verbose_name="nombre d'heure effectuée par le salarié") Thank you for your answer ! -
How to transfer a file to the converter function
I am looking for a way to transfer a file to a function that converts different formats to pdf. The transfer takes place at the moment of saving the source file to AWS S3 inside the perform_create() function. When I pass a file stored on the local machine to the function manually everything works. class DocumentsListView(AwsUrlMixin, viewsets.ViewSetMixin, generics.ListCreateAPIView): ..... ..... def perform_create(self, serializer): file = serializer.validated_data['filedata'] name, ext = os.path.splitext(file.name) random_name = uuid.uuid4().hex file.name = f'{random_name}{ext}' url = self._get_aws_url(file)#get the link to private S3 directory for file download or view if ext != 'pdf': directory = os.path.abspath(os.path.dirname(__file__)) convert_to_pdf(file, directory) serializer.save(author=self.request.user, url_link=url) models.py class Documents(models.Model): .... filedata = models.FileField(storage=PrivateMediaStorage()) url_link = models.URLField(default=None, blank=True, null=True) convert_function.py from subprocess import Popen LIBRE_OFFICE = '/usr/lib/libreoffice/program/soffice' def convert_to_pdf(input_docx, out_folder): p = Popen([LIBRE_OFFICE, '--headless', '--convert-to', 'pdf', '--outdir', out_folder, input_docx]) print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx]) p.communicate() I got an error File "/home/y700/anaconda3/lib/python3.7/subprocess.py", line 1447, in _execute_child restore_signals, start_new_session, preexec_fn) TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile I've also tried this way (using url instead of file instances as an argument for the function convert_to_pdf) def perform_create(self, serializer): file = serializer.validated_data['filedata'] name, ext = os.path.splitext(file.name) random_name = uuid.uuid4().hex file.name = f'{random_name}{ext}' url = self._get_aws_url(file) if ext != … -
I am trying to print the message that appears in the sql server management in a text area in my html in django
I am trying to print the message that appears in the sql server management in a text area in my html in django This is the message that I want it to be in my Html This is the Text Area that I the message will be -
How add values to child form by parent ID?
This is my model class User(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Phone(models.Model): user = models.ForeignKey(Osoba, editable=False, related_name='phone', on_delete=models.CASCADE) phone = models.CharField(max_length=50) and i want to add phone to current User selected by ID and display it on site i have tried that def create_phone(request, id): user = User.objects.get(id=id) form = PhoneForm(request.POST or None, instance=user) if form.is_valid(): form.save() return redirect('list_users') return render(request, 'index-phone.html', {'form': form}) But it doesnt work, when i click button, its not creating new Phone My urls urlpatterns = [ path('', list_users, name='list_users'), path('new', create_user, name='create_user'), path('/<int:id>/update', update_user, name='update_user'), path('/<int:id>/delete', delete_user, name='delete_user'), path('/<int:id>/', create_phone, name='create_phone') ] -
Django: Move calculations query set, away from Python code
In the following code snippet, my goal is to get outstanding_event_total_gross. To get that I first lookup for each ticket that belongs to the event the amount of sold_tickets. Out of that, I can calculate tickets_left. For each ticket I then calculate the outstanding_ticket_total_gross which I add up to outstanding_event_total_gross. A lot of the business logic happens in Python, but I wonder now if there is a more efficient query set to achieve what I am doing while calling the data from the database? tickets = Ticket.objects.filter(event=3) outstanding_event_total_gross = 0 for ticket in tickets: sold_tickets = ticket.attendees.filter( canceled=False, order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE, ), ).count() tickets_left = ticket.quantity - sold_tickets outstanding_ticket_total_gross = tickets_left * ticket.price_gross outstanding_event_total_gross += outstanding_ticket_total_gross print(outstanding_event_total_gross) -
Django Channels equivalent to reverse()
In regular Django, I know I can use reverse to reverse a url. Is there equivalent functionality in django-channels for reversing a websocket url. If I have the following routing application = ProtocolTypeRouter({ "websocket": URLRouter([ url(r"^foo-websocket/$", FooConsumer, name="foo-example") ]), }) Is there something I can call like >>> reverse("foo-example") "/foo-websocket/" Or is this not possible in django-channels? -
How to properly unit test a Django middleware
I have to write unit tests for several Django Middlewares (Django > 1.10 styled middlewares). Project is an API, done with Django==2.2.3 and djangorestframework==3.9.4, I'm using standard Django unit testing module, and APIRequestFactory() and APIClient() test functions from Django REST framework to create mock requests for my tests. Here is an example of one middleware I want to test: from . import models class BrowserId(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if hasattr(request, 'COOKIES') and 'mydomain.bid' in request.COOKIES: bid = request.COOKIES.get('mydomain.bid', None) else: bid = None request.bid = models.BrowserId(bid) if bid else models.BrowserId.random() response = self.get_response(request) response.set_cookie( conf.BID_COOKIE_KEY, value=request.bid, max_age=conf.COOKIE_MAX_AGE, domain=conf.BID_COOKIE_DOMAIN ) return response I want to test: * That browser ID has successfully been added to the request * That cookie has successfully been set on the response ...independently of others middlewares. So, to be more precise, part of the tests would vaguely have to look like this: from rest_framework.test import APIRequestFactory, APIClient, APITestCase from my_api.auth import middlewares, models class MiddlewaresTestCase(APITestCase): def test_fresh_browser_id_request(self): ??? SOME CODE TO PROCESS THE REQUEST BY THE MIDDLEWARE assert hasattr(request, 'bid') assert len(request.bid) == 30 def test_existing_browser_id_request(self): req = APIRequestFactory().get('/') mock_bid: str = 'abcd1234' req.COOKIES = {cookie_key: mock_bid} ??? SOME CODE … -
How to operate a model in django without not define?
There are two projects, the A project defines each model, and the B project queries and modifies the model of the A project. How to do it? A project: class Case(models.Model): is_active = models.BooleanField(default=False) B project: I thought like this, but I don't know how to continue: class Base(models.Model): pass def save(self, force_insert=False, force_update=False, using=None, update_fields=None): pass -
How to avoid populating previous field value when click add another in formset
I have used formset to add some contents to model. When i click edit, i can use add another or delete link to add or delete content. But when i click add another its populating with previous data. How to avoid that data? I tried using initial but its shows error. ChoiceFormset1 = inlineformset_factory( Course, Materials_pdf, form=Materials_pdfForm, extra=0, intial =[{'chapter':'test'},{'pdf':'test'}, {'course_type':'test'}] can_delete=True, fields=('chapter','pdf','course_type') ) what i wanted is new fields which is not populated with previous data, when i click add another. Please help me to find a solution. -
How do I code in HTML get an image from a media server running on the same host as apache server
I'm running a UI to control some sensors using a Django Web app on apache2 on port 80 of a raspberry pi. I need to integrate streaming video into the app. I'm using MJPG-streamer as my streaming video server on port 8080 of the same machine. On the streaming video server site the html to get the image is: . Is there a way to code a reference to this in my DJango UI on the apache server? -
Use the "Add More" functionality to a page(template) without submitting the existing form (and values) and submitting in the end
I have a ModelForm which asks for his dreams from the users. But I want users to provide with the "Add More" button so that they can submit the form (form fields) all at once without being the headache of reloading the page everytime the user presses ADD More For example, If a user is done with telling its one wish, he/she can n number of more wishes and once he/she presses Submit , the form should then submit the answer to the DB. How can I make a model for this? Will a single class Wish(model.Model): user=models.Foreignkey(User, on_delete=models.CASCADE) wishes= models.Charfield(max_length=1024) and a form from this model to render the form???? A user can have any number of wishes available in the DB so that he/she can delete at any point of time by checking/unchecking. -
when i run python manage.py migrate getting ValueError: String input unrecognized as WKT EWKT, and HEXEWKB please do
when i made manage.py migrations i went sucessfully but when i run manage.py migrate i am new to geodjango pls help me Settings.py import os if os.name=='nt': import platform OSGEO4W=r"C:\OSGeo4w" if '64' in platform.architecture()[0]: OSGEO4W+="64" assert os.path.isdir(OSGEO4W), "Directory does not exist:"+OSGEO4W os.environ['OSGEO4W_ROOT']=OSGEO4W os.environ['GDAL_DATA']=OSGEO4W+r"\share\gdal" os.environ['PROJ_LIB']=OSGEO4W+r"\share\proj" os.environ['PATH']=OSGEO4W+r"\bin;"+os.environ['PATH'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '+2r35-w0_kqcr4ygbt474-!xx9q9izus$-+)g)%(-+=8d*^1pt' DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'repoter', ] 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 = 'agricon.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'agricon.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgis_25_sample', 'USER': 'postgres', 'PASSWORD': 'Shanmukhavarma99@', 'HOST': 'localhost', 'PORT': '5432', } } GEOS_LIBRARY_PATH = r'C:\\OSGeo4W\\bin\\geos_c.dll' GDAL_LIBRARY_PATH = r'C:\OSGeo4W\\bin\\gdal204.dll' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation. UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' LEAFLET_CONFIG={ 'DEFAULT_ZOOM':1, 'MAX_ZOOM':30, 'MIN_ZOOM':10, 'SCALE':'both', } in models.py applied this to get welcome table python manage.py ogrinspect #repoter/data/TM_WORLD_BORDERS-0.3.shp welcome --srid=4326 --multi --mapping from django.db import models from … -
the content of Django form is not showing
I am little new to programming and I am trying to make the home page and login page in the same page the email and the password field are not showing index.html <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt=""> </div> <div class="col-md-4"> <form method="POST"> {% csrf_token %} {{ form }} <div class="form-check"> <span class="fpswd">Forgot <a href="#">password?</a></span> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> app/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from homePage.forms import SignInForm # Create your views here. def homePage(request): if request.method == 'POST': sign_in_detail = SignInForm(request.POST) if sign_in_detail.is_valid(): return render(request, "index2.html",{}) else: sign_in_detail = SignInForm() return render(request, "index.html",{"form":'sign_in_detail'}) app/forms.py from django import forms from django.core import validators class SignInForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={ "class": 'form-control', "placeholder":'Enter E-mail', "id": 'exampleInputEmail1' }) ) password = forms.PasswordInput( attrs={ "class":'form-control', "placeholder":'Enter Password', "id":'exampleInputPassword1' }) the output is just a string "sign_in_detail" -
create method is raising key error in serializer
I am creating an API for signup. Serializers.py class UserSignupSerializer(serializers.Serializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'role'] extra_kwargs = {'password': {'write_only': True}} def create(self, validate_data): user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username']) user.set_password(validate_data['password']) user.save() return user Views.py class UserSignupView(APIView): def post(self, request): serializer = UserSignupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_204_NO_CONTENT) But this is giving key error 'email' or anything I put first in this line: user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username']) -
how can i pass get values to specific models fields in views.py
How to pass request.GET.get value to another form in django. def bacadmininvitoBid_views(request): project_list = ProjectNameInviToBid.objects.all() query = request.GET.get('query') if query: project_list = project_list.filter(ProjectName__icontains=query) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) if form.is_valid(): form.ProjectName = project_list form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'form': form, 'project_list': project_list } return render(request, 'content/invitoBid/bacadmininvitoBid.html', args) i want to pass it to ProjectName field -
unable display profile details through signup only admin login profile displaying?
I'm new to django i created signup form when i enter the data it will saved to database login also fine but only saving admin user details not saved our table details in admin thats the resion try to display profile details only user details displaying suppose i enter data through admin all details will displaying in profile views.py -------- from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from testapp.forms import signupform from django.contrib.auth.hashers import check_password from testapp.models import Userprofile def homeview(request): return render(request,'testApp/home.html') @login_required def feedbackview(request): return render(request,'testApp/feedback.html') def logoutview(request): return render(request,'testApp/logout.html') def akhilview(request): return render(request,'testApp/akhil.html') def siriview(request): return render(request,'testApp/siri.html') def depview(request): return render(request,'testApp/dep.html') def subview(request): return render(request,'testApp/sub.html') @login_required def view_profile(request, pk=None): if pk: user = Userprofile.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'testApp/profile.html', args) def register(request): form=signupform() if request.method=='POST': form=signupform(request.POST) if form.is_valid(): user=form.save() user.set_password(user.password) user.save() return redirect("/accounts/login") else: print(form.errors) else: form=signupform() # return HttpResponseRedirect('/accounts/login') return render(request,'testapp/singup.html',{'form':form}) forms.py ------- from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core import validators class signupform(forms.ModelForm): name=forms.CharField(max_length=25) password = forms.CharField(max_length=32, widget=forms.PasswordInput) phone = forms.IntegerField() date_of_birth=forms.DateTimeField(help_text='DD/MM/YYYY H:M',input_formats=['%d/%m/%Y %H:%M']) gender = forms.CharField(max_length=10, required=True) age = forms.IntegerField() … -
Not able to created nested comment functionality using django rest framework
I am trying to make a nested comment functionality using django rest framework. I am using Django 2.2 and rest framework version 3.10.2 but here i am following a video in youtube that uses Django 1.9. No matter what value i passed in URL, it always return a validation error stating that model_qs is empty. I am not able to solve this issue. Can someone please look into it and let me point out what i am doing wrong here. from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType urls.py urlpatterns = [ path('create/', CommentCreateAPIView.as_view(), name='create'), ] model.py class CommentManager(models.Manager): def all(self): qs = super(CommentManager, self).filter(parent=None) return qs def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs def create_by_model_type(self, model_type, slug, content, user, parent_obj=None): model_qs = ContentType.objects.filter(model=model_type) if model_qs.exists(): some_model = model_qs.first().model_class() obj_qs = some_model.objects.filter(slug=slug) if obj_qs.exists() and obj_qs.count() == 1: instance = self.model() instance.content = content instance.user = user instance.content_type = model_qs.first() instance.object_id = obj_qs.first().id if parent_obj: instance.parent = parent_obj instance.save() return instance return None class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) … -
Form after registration is not submitting Django
To complete registration, I want users to complete secondary form. However secondary form is not submitting. I think user is not getting authenticated in the registration and then the secondary form is not submitting. The login() seems to not work. # the form in this view that's not submitting def agreements(request): if request.method == "POST": form = AgreementsForm(request.POST) if form.is_valid(): user = request.user agree = form.save(commit=False) agree.save() else: raise ValidationError("Form is not valid. Try Again.") else: form = AgreementsForm() return render(request, 'agree.html', {'form': form}) Here is the forms.py for the agreements: class AgreementsForm(forms.ModelForm): non_ent=forms.BooleanField(label='kdmkl kdldsk') agreement1=forms.BooleanField(label='dmklsd. lkdfmld') class Meta: model = Agreements fields = ('non_ent', 'agreement1') def save(self, commit=True): agree = super(AgreementsForm, self).save(commit=False) agree.non_ent = self.cleaned_data['non_ent'] agree.agreement1 = self.cleaned_data['agreement1'] if commit: agree.save() return agree Here is the initial registration view: # register view which submits, but I think it's not authenticating the user def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('agreements_page') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) -
have different base image for an application in docker
I am new in docker world.I am trying to understand Docker concepts about parent images. Assume that I want to run my django application on docker. I want to use ubuntu and python, I want to have postgresql as my database backend, and I want to run my django application on gunicorn web server. Can I have different base image for ubuntu, python, postgres and gunicorn and create my django container like this: FROM ubuntu FROM python:3.6.3 FROM postgres FROM gunicor ... I am thinking about having different base image because if someday I want to update one of these image, I only have to update base image and not to go into ubuntu and update them. -
Django dynamic filter the data base on dropdown select
Having trouble selecting data based on the dynamic dropdown list. Save the user data and being populated as a list. Couple questions: how to bring data from the AddData into SiteData Also when user select the dropdown code from the SiteData, How to associate or populate data only for that SiteData how to map the data code with site_ip, site_prefix, site_data1,site_data2 Also noticed, when selecting dropdown, I get the value as number not the text name.. for example: site 68 site_ip 1 MODEL class Code (models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True, error_messages={'unique':"Already in Used"}) def __str__(self): return self.name class AddData (models.Model): code = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) data1_ip = models.GenericIPAddressField(protocol='IPv4', unique=True, error_messages={'unique':"Already in Used"}) data2_prefix = models.CharField(max_length=2, default='22') def __str__(self): return self.data1_ip class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) site_ip = models.ForeignKey(AddData, on_delete=models.CASCADE, null=True) site_prefix = models.ForeignKey(AddData, on_delete=models.CASCADE, null=True) site_data1 = models.CharField(max_length=3, default='120') site_data2 = models.CharField(max_length=1, default='1') FORM class CODE_Form(forms.ModelForm): class Meta: model = Code fields = ('name',) class AddData_Form(forms.ModelForm): class Meta: model = MIDTIER_Add_Site fields = ('code', 'data1_ip', 'data2_prefix',) class SiteData_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(SiteData_Form, self).__init__(*args, **kwargs) if 'site' in self.data: c = self.data.get('site') c_ip = self.data.get('site_ip') self.fields['site'] = forms.ModelChoiceField(queryset=CODE.objects.filter(name=c)) self.fields['site_ip'] = forms.ModelChoiceField(queryset=CODE.objects.filter(name=c_ip)) class Meta: model = … -
Permission Denied when attempting to start Daphne systemctl process
I'm deploying a website using Django and Django-Channels, with Channel's daphne ASGI server substituting for the typical Gunicorn WSGI setup. Using this Gunicorn WSGI tutorial as a jumping off guide, I attempted to write a systemctl service for my daphne server, when I hit the below error: CRITICAL Listen failure: [Errno 13] Permission denied: '27646' -> b'/run/daphne.sock.lock' I was unfortunately unable to find any answers to why permissions would be denied to the .sock file, (in context to Daphne) so I was hoping I could get some hints on where to begin debugging this problem. Below are my daphne.socket and my daphne.service files. daphne.service [Unit] Description=daphne daemon Requires=daphne.socket After=network.target [Service] User=brianl Group=www-data WorkingDirectory=/home/brianl/autoXMD ExecStart=/home/brianl/autoXMD/env/bin/daphne -u /run/daphne.sock -b 0.0.0.0 -p 8000 autoXMD.asgi:application [Install] WantedBy=multi-user.target daphne.socket [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne.sock [Install] WantedBy=sockets.target Based off the linked DigitalOcean tutorial, I start my service with sudo systemctl start daphne.socket. My guess is that there's some kind of discrepancy between setting up systemctl services for Gunicorn and Daphne that I missed, but I don't know for sure. (If it helps, I'm planning on using Nginx as the main server, but I haven't reached that point yet)