Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Variable is unused even tho it is used
The Variable post_added is unused, even tho I use it later in the code. I really can't figure out where the problem is supposed to be def post_comment_create_and_list_view(request): qs = Post.objects.all() profile = Profile.objects.get(user=request.user) p_form = PostModelForm() c_form = CommentModelForm() post_added = False profile = Profile.objects.get(user=request.user) if 'submit_p_form' in request.POST: print(request.POST) p_form = PostModelForm(request.POST or None, request.FILES) if p_form.is_valid(): instance = p_form.save(commit=False) instance.author = profile instance.save() p_form = PostModelForm() post_added = True more code -
How to check if Place is near to My driving route in GeoDjango
I want to check weather a given location (Point of Interest) is in the certain range of my Driving Route(LineString). I guess bbcontains, bboverlaps are the options but not sure since there are no video tutorials of GeoDjango. Leaving useful link below if someone can help me out here. bbcontains&bboverlaps I seen some where that an envelope can be drawn around a linestring but now unable to get the link on internet. Any help would be appreciated. Thanks :) -
How to link Django User model to certain Post models
So let's say I have a model called "Post" that looks like this: class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() def __str__(self): return self.title now, say I have an option for users to create a Post on my site. How could I alter the standard User model and give it a characteristic containing all of the posts that that user has created. For example, say we have a user who has created a post. In the interactive shell that Django has, I could enter "user.posts" and It would pull up all the posts that that user has created. How could I go about this? -
I am getting an error while uploading my Django app to server
2020-10-10T15:33:00.962648+00:00 heroku[web.1]: Process exited with status 3 2020-10-10T15:33:01.005314+00:00 heroku[web.1]: State changed from up to crashed 2020-10-10T15:33:01.408833+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=writingroom.herokuapp.com request_id=c6148721-26bb-4fac-83bf-4acd4ea1365b fwd="176.233.99.0" dyno= connect= service= status=503 bytes= protocol=https Restarting dynos on ⬢ writingroom... done PS D:\visual_studio_code\python1\django\my_blog> heroku open I am getting an error while uploading my Django app to server(error code=H10 desc="App crashed" method=GET path="/" ) -
Django selected value using manual render form in django
I'm trying to implement CRUD operations in django, however, I'm stuck in the edit operation. After passing the data to edit template I need to show the selected values of operating system dropdown list, how can I achieve that? I utilized the manual rendering of django form with the following code in the template: <div class="form-group row"> <label class="col-sm-3 col-form-label">Operating System</label> <div class="col-sm-9"> <select class="form-control" name="os_id" id="os_id" required> <option value="">--Select--</option> {% for os in os %} <option value="{{ os.id}}">{{ os.key_name}}</option> {% endfor %} </select> </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label">Title</label> <div class="col-sm-9"> <textarea class="form-control" id="title" name="title" rows="3" required>{{ servicedesk.title }}</textarea> </div> </div> here's the view code: def edit(request, id): servicedesk=Servicedesk.objects.get(id=id) softwares=Software.objects.all os=OperatingSystem.objects.all context = {'servicedesk':servicedesk, "softwares":softwares, "os":os} return render(request, 'servicedesks/edit.html', context) and the model: class OperatingSystem(models.Model): key_name = models.CharField(max_length=100,null=True) key_description = models.CharField(max_length=255,null=True) class Meta: db_table = "operating_systems" def __str__(self): return self.key_name class Software(models.Model): key_name = models.CharField(max_length=100,null=True) key_description = models.CharField(max_length=255,null=True) class Meta: db_table = "softwares" def __str__(self): return self.key_name class Servicedesk(models.Model): os_id=models.ForeignKey(OperatingSystem, on_delete=models.SET(0)) software_id = models.ForeignKey(Software, on_delete=models.SET(0)) title = models.CharField(max_length=255,null=True) I tried this but it's not working: <div class="form-group row"> <label class="col-sm-3 col-form-label">Operating System {{os_id}}</label> <div class="col-sm-9"> <select class="form-control" name="os_id" id="os_id" required> <option value="">--Select--</option> {% for os in os … -
How to make chrome webmanifest point to the right png located in Django static directory
I'm trying to add a favicon package to my website but I can't make the webmanifest point to the right source that is: static/favicon/android-chrome-192x192.png When using "src":"static/favicon/android-chrome-192x192.png" it points to static/favicon/static/favicon/android-chrome-192x192.png and when using "src":"android-chrome-192x192.png" it points to /android-chrome-192x192.png This is the webmanifest: { "name": "I.R Portfolio", "short_name": "I.R", "icons": [ { "src": "static/favicon/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "static/favicon//android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone" } And this is the HTML: <link rel="manifest" href="{% static 'favicon/site.webmanifest' %}"> I would be really grateful if someone could point me to the right documentation/answer or have a solution, I couldn't find anything regarding this. -
Resize imgaes Django
I have modek `from tempfile import NamedTemporaryFile #models.py upload_path = 'images' class Image(models.Model): image = models.ImageField(upload_to=upload_path, blank=True, null=True) image_url = models.URLField(blank=True, null=True) def clean(self): if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ): raise ValidationError('Empty or both blanked') def get_absolute_url(self): return reverse('image_edit', args=[str(self.id)]) def save(self): if self.image_url and not self.image: name = str(self.image_url).split('/')[-1] img = NamedTemporaryFile(delete=True) img.write(urlopen(self.image_url).read()) img.flush() self.image.save(name, File(img)) super(Image, self).save() This model loads the link url into the ImageField. #forms.py class ImageForm(ModelForm): class Meta: model = Image fields = ['image', 'image_url'] This is my form to add images. #views.py class DetailImage(UpdateView): model = Image form_class = ImageForm template_name = 'image_edit.html' context_object_name = 'image' How can I resize images so that the original files are retained, and only images changed in width and height are displayed in the backend? -
How to render variable to template in Django app
I'm developing Django app. I want to render variable "q_word" to the template from this views.py class DbList(ListView): model = TestEu paginate_by = 10 def get_queryset(self): q_word = self.request.GET.get('query') if q_word: sql = 'select * from test_eu' sql += " where eng_discription ~ '.*" + q_word +".*'" object_list = TestEu.objects.raw(sql) return object_list Since "get_queryset" function apply "self" as first argument def get_queryset(self): I don't know how to apply below code to render. return render(request, 'detail.html', {'q_word': q_word}) -
My app is not recognising AUTH_USER_MODEL as the default User model
I have created a custom User model. My model is as follow: class User(AbstractUser): ... Name = models.CharField(max_length=128) ... When I try to make a post request to this model through my app, in the views.py file I have code that goes like this: def post(self,request): name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] age = request.POST['age'] number = request.POST['number'] gender = request.POST['gender'] organisation = request.POST['organisation'] designation = request.POST['designation'] u = User( Name = name, ... I get an error that goes like this: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/adhishwars/Desktop/simulations/beergame/views/instructor.py", line 37, in post u = User( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 500, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: User() got an unexpected keyword argument 'Name' I made sure I included AUTH_USER_MODEL = 'app.User' in the settings.py file at the beginning of the project before I applied any migrations. Yet I still … -
After Upgrading of new version of python 3.9 ! why i am getting that type of error.Too much annoying.?
I am getting that error after upgradation of python new version 3.9 . fatal python error: init_import_size: failed to import the site module -
DRF Updating an existing model after adding values to non existing fields
I am trying to create a bet app so that user can create bet and challenge other . But when I am unable to create a new bet since I am placing the user who accepted the bet on the same model: this is how my model looking like . class CreateBet(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="bets",null=True, on_delete=models.CASCADE) bet_name= models.CharField(max_length=255) amount = models.CharField(max_length=255) scheduled_datetime = models.DateTimeField(null=True,blank=True) accepted_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,related_name="accept",null=True) status = models.BooleanField(default=False) so what I want is whenever I hit: router.register('api/bets',BetViewset,'userbets') this end point I want user to create a bet without adding to fields accepted_user and status . But if the user hit: router.register('accept_bet',AcceptBetViewset,'accept') this end point both the accepted_user will be created and status will be set to True. currently my serializer looking like this class BetCreateSerializer(serializers.ModelSerializer): class Meta : model = CreateBet exclude = ['accepted_user','status'] and its api: class BetViewset(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = BetCreateSerializer def perform_create(self,serializer): serializer.save(owner = self.request.user) def get_queryset(self): today = datetime.date.today() return CreateBet.objects.filter(scheduled_datetime__date=today) which works perfectly fine . but whenever I tried with this serializer : class AcceptBetSerializer(serializers.ModelSerializer): bet = BetCreateSerializer(many = True , read_only= True) class Meta: model = CreateBet fields ='__all__' # def update(self, instance, validated_data): # id = validated_data.pop('id') … -
Will Windows Server 2012 work with Django 3.1.2?
I would like to know if somebody has recently worked with Windows Server 2012 & Django 3.1.2. Are they compatible? Will there be any issues? -
Running a Django/Gunicorn app locally using Docker fails with ERR_CONNECTION_REFUSED
My Dockerfile, shown here, deploys to Google App Engine flex and runs with no problems. FROM gcr.io/google-appengine/python RUN apt-get update && apt-get install -y \ binutils \ gdal-bin \ python-gdal RUN virtualenv /env -p python3.6 ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt RUN mkdir -p -m775 uploads ADD . /app CMD exec gunicorn -b :$PORT mysite.wsgi I can also run the application locally by getting into the virtual environment and: python manage.py runserver This allows me to view it in a browser at http://localhost:8000/ and also access the API locally. However, my problem is when I run the application locally using docker. When I go to http://0.0.0.0:8000/, I always receive an ‘ERR_CONNECTION_REFUSED’ error. I’ve tried various iterations of: docker run --entrypoint=/bin/bash django -c "python manage.py runserver 0.0.0.0:8000" and docker run --entrypoint=/bin/bash django -c "p["gunicorn", "--bind", ":8000", "--workers", "3", "mysite.wsgi:application"] And I have tried changing my Docker file cmd (and rebuilt the image) to: CMD ["python", "manage.py", "runserver", "0.0.0.0", "8000"] And ENTRYPOINT [ "python", "manage.py" ] #CMD [ "runserver", "127.0.0.1:8000" ] CMD [ "runserver", "0.0.0.0:8000" ] But keep getting the same ‘ERR_CONNECTION_REFUSED’ error I’ve been thru all the SO related questions I could find … -
django creating Profile with custom company fields
i have two forms (OwnerCreateForm, EmployeesCreateForm) and 3 models (Profile, Company). when owner signup he creates the company and his own User object. after the owner login, he can created Employees. i need to associate the owners company to the employees. here is the models i'm using: class Company(models.Model): company_name = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=100) def __str__(self): return self.company_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.ForeignKey(Company, on_delete=models.CASCADE) is_owner = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) is_systemAdmin = models.BooleanField(default=False) def __str__(self): return '{} Profile'.format(self.user.username) and here the forms: from django.contrib.auth.forms import UserCreationForm from .models import Company from django import forms class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('company_name', 'address') class OwnerCreateForm(UserCreationForm): class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = "Email Address" class EmployeesCreateForm(UserCreationForm): is_admin = forms.BooleanField(required=False) is_manager = forms.BooleanField(required=False) is_systemAdmin = forms.BooleanField(required=False) class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = "Email Address" and here is my views: from django.shortcuts import render, redirect from .forms import OwnerCreateForm, EmployeesCreateForm, … -
Is there a way to implement the group function as in Facebook group in Django?
I’m looking to build a community management tool, which partially is quite similar to how the Facebook (private) Groups works. Is there any existing group application in Django to achieve such function, so that use could create, view, and manage their own group? Thanks in advance :) will be looking to refine my question more if required! -
How to use Django url template in a Javascript file
I'm using Django 3.1 and I would like to know how to use Django URL template in a Javascript file. I'm trying to implement AJAX and when I try to open the connection using the following command in a Javascript file (not inside a script tag in an HTML file): var xmlhttp = new XMLHTTPRequest(); xmlhttp.open("GET", "{% url 'checkUser' %}?username=" + encodeURIComponent(username.value), true); The template is not parsed. But if I use the Javascript code inside a script tag in an HTML file, it works fine. Is it possible to use the Django templates in a JS file? How? -
How to display English to Persian numbers in Django
How to display English numbers in Persian in Django? for example: English numbers: 0 1 2 3 4 5 6 7 8 9 Persian numbers: ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ -
Cannot access pg_config on virtualenv python
I have a problems when try to install pip install psycopg2 the errors is Error: pg_config executable not found. but when I try access pg_config from normal terminal (not in virtualenv mode), I can access the pg_config Anyone can help ? Screenshot of pg_config not found on venv, but found on normal terminal mode -
Stripe Django invalid parameter
I am getting 'invalid parameter' statement when I use the test stripe creditcard(4242) with Django. The following is my code for Views. I dont now what I am doing wrong. I think I am mistaking with the amount part or the token part. class PaymentView(View): def get(self, *args, **kwargs): return render(self.request, 'appname/payment.html') def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100)#cents try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) #create payment payment = payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() #assign the payment to the order order.ordered = True order.payment = payment order.save()``` -
How to use Bootstrap 4 popover dynamically in Django?
I have a simple Django app similar to a quiz app. I have stored all the questions with answers in the database. Then, I retrieve all the questions in a template using Django ListView. Each question has 4 options and one answer field. Initially, I want to hide the answer and use a Bootstrap 4 popover. When a user click on the popover button the answer will display. I have done all but the popover is not showing the answer when I click the button. Below is my code - <div class="col-md-12 card border-0 mb-2 mt-3 ml-1"> <div class="card-body pl-0 pt-3"> {% for topic in topic_list %} <h2 class="mt-0 mb-0">{{ topic.name }}</h2> {% for question in topic.question_set.all %} <h6 class="mb-4">{{ question.serial_no }}. {{ question.name }}</h6> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(A) {{ question.option1 | safe }} </label> </div> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(B) {{ question.option2 | safe }} </label> </div> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(C) {{ question.option3 | safe }} </label> </div> <div class="form-check ml-3 mb-4"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(D) {{ question.option4 | safe }} </label> </div> <button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="right" data-content="{{ question.answer }}"> … -
Django multiple file upload via modelform and manytomany field outputting file contents instead of uploading
I'm trying to setup a single field in a model that allows multiple file to be uploaded, using a ModelForm. I've been googling this for the last few hours and it seems a manytomany field is the preferred approach. I'm testing it works with some teext files containing just a few characters. The output of form.errors gives something like "b'gggf'" is not a valid value. where one of the files I attempt to upload is b.txt, with gggf being the contents. I would like to know what is causing this and where I am going wrong. The relevant parts of my app are below: models.py: def filename_path(instance, filename): return os.path.join('new_applicant_documents/%s_%s/%s' % (instance.last_name, instance.first_name, filename)) class NewApplicant(models.Model): documents = models.ManyToManyField('NewApplicantDocument') class NewApplicantDocument(models.Model): documents = models.FileField(upload_to=filename_path) forms.py: class NewApplicantForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewApplicantForm, self).__init__(*args, **kwargs) class Meta: model = NewApplicant fields = ['documents'] widgets = {'documents': forms.ClearableFileInput(attrs={'multiple': True}),} views.py: def newapplicant(request): form = NewApplicantForm() if request.method == "POST": form = NewApplicantForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() return render(request, 'newapp/thankyou.html', {}) else: form = NewApplicantForm() return render(request, 'newapp/appform.html', {'form': form}) My form is defined with enctype="multipart/form-data" and works fine when uploading individual files (prior to implement the manytomany field). -
User Login API Does not work! Django the code always show "Email or Password Invalid" message
Where is the error I will show you serializers.py and views.py It is not a syntax error But I think something went wrong in the code! In serializers.py class UserLogin(serializers.ModelSerializer): email=serializers.EmailField(max_length=50, required=True) password=serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ('email','password') def validate(self,data): email=data.get('email') password=data.get('password') if email and password: auth=authenticate(email=email, password=password) if auth: return auth else: raise exceptions.ValidationError('Email or Password Invalid') else: raise exceptions.ValidationError('fill all the fields') In views.py class LoginView(APIView): def post(self, request, format='json'): serializer = UserLogin(data=request.data) serializer.is_valid(raise_exception=True) objectuser = serializer.validated_data token, _ = Token.objects.get_or_create(user=objectuser) return Response(token.key, headers={"Access-Control-Allow-Origin": "*"}) -
Array input in html
Can I use Input of html to access array elements with single input box.[views.py][1] -
It is a python Django project can't able to place order in checkout form
ValueError Incorrect AES key length Request method: post Exception type:value error GetMethod is not intialized -
VScode debugger with docker-compose
Recently i have started using docker for my project running with the following Django Nginx Gunicorn Celery Postgres Redis Earlier it was easy to setup debugger but after using docker-compose i am not able to do that. As soon as i start the debugger it loads for sometime and then automatically stops with no logs or error anywhere. Here are the relevant code. launch.json { "configurations": [ { "name": "Python: Remote Attach", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 443 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] } ] } docker-compose.yml version: '3' services: db: image: postgres:12 env_file: .env environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} ports: - "5431:5432" volumes: - dbdata:/var/lib/postgresql/data nginx: image: nginx:1.14 ports: - "443:443" - "80:80" volumes: - ./config/nginx/:/etc/nginx/conf.d - ./myapp/static:/var/www/myapp.me/static/ web: restart: always build: ./myapp command: bash -c " python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn --certfile=/etc/certs/localhost.crt --keyfile=/etc/certs/localhost.key myapp.wsgi:application --bind 0.0.0.0:443 --reload" expose: - "443" depends_on: - db - nginx env_file: - .env volumes: - ./myapp:/opt/myapp - ./config/nginx/certs/:/etc/certs - ./myapp/static:/var/www/myapp.me/static/ broker: image: redis:alpine expose: - "6379" celery: build: ./myapp command: celery -A myapp worker -l info env_file: - .env volumes: - ./myapp:/opt/myapp depends_on: …