Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix it please
i need to show the test in image variable but he give me just None def test(request): qr = pyqrcode.create('1') image = qr.png('1.png', scale=7) return HttpResponse(image) -
Python and Django Source Code Navigation in Emacs
I am wondering if there is a way to to navigate Python(Django) code in Emacs similar to how one can M-. for Common Lisp code when using SLIME. I have installed ELPY and a mode called python-django. However, they do not seem to provide this functionality. I am particularly interested in doing this why developing using Django. However, even navigation for standalone Python projects would be nice. -
How to fix TypeError: 'module' object is not iterable
The error will not allow me to run the server. Pls help me. I tried - python manage.py runserver in Windows PowerShell. But still the result is what is captured on the code section below. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python35-32\lib\site-packages\django-2.2.1-py3.5.egg\django\urls\resolvers.py", line 581, in ur l_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python35-32\lib\site-packages\django-2.2.1-py3.5.egg\django\urls\resolvers.py", line 581, in ur l_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python35-32\lib\site-packages\django-2.2.1-py3.5.egg\django\urls\resolvers.py", line 588, in ur l_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'djangoproject.urls' does not appear to have any patte rns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Getting an error when doing get_or_create in MYSQL db?
I have a Django app, using an AWS RDS MYSQL instance. Below is from my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'username', 'PASSWORD': 'somepass', 'HOST': 'mydb.XXXXXXXX.us-east-2.rds.amazonaws.com', 'PORT': '3306', 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'; \ SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED",}, } } Below is the code that causes the issue for i in data: poll, created = Poll.objects.get_or_create(topic=i['topic'], question=i['question']) I am not sure what the error is, but this is offending line. Commenting it out causes the app to run. The error in get_or_create is resulting in a 500 error in the backend call that contains this code. I have rebooted the RDS instance since changing OPTIONS in DATABASES, and that did not help. -
Continuing Django-haystack filters on pagination
I'm trying to set up pagination within my Django project but I can't find a way to make the filters (ptags in my case) follow to the next pages. I have a custom forms.py from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs That I pass in my Views: class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 3 context_object_name = 'object_list' Here's my full search_result.html: <div> {% if page_obj.object_list %} <ol class="row top20" id="my_list"> {% for result in page_obj.object_list %} <li class="list_item"> <div class="showcase col-sm-6 col-md-4"> <div class="matching_score"></div> <a href="{{ result.object.get_absolute_url }}"> <h3>{{result.object.title}}</h3> <h5>{{ result.object.destination }}</h5> <img src="{{ result.object.image }}" class="img-responsive"> </a> <div class="text-center textio"> <ul class="tagslist"> <li class="listi"> {% for tags in result.object.ptags.names %} <span class="label label-info"># {{ tags }}</span> {% endfor %} </li> </ul> </div> </div> </li> {% endfor %} </ol> </div> I'm able to pass the query which is a destination to … -
Change choice field of model in django view
I have multiple field choice in my model. I want to change the value of statue in my view. I read These article and this question.In those link, 2 way assumed: create another model MultipleChoiceField What I must do, If I want to use MultipleChoiceField? I read these links: 1 , 2, 3 ,4, 5 ,and 6 ;but non of them cloud help me and I can't understand anything. Also this is my codes: #models.py STATUE_CHOICE = ( ('draft', 'draft'), ('future', 'future'), ('trash', 'trash'), ('publish', 'publish'), ) statue = models.CharField(max_length=10, choices=STATUE_CHOICE) #views.ppy def delete_admin_trash_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method =="POST": form = AddPostForm(request.POST, instance=post) post.statue = 'trash' return redirect('view_admin_post') else: form = AddPostForm(instance=post) template = 'blog/admin_blog/delete_admin_trash_post.html' context = {'form': form} return render(request, template, context) Is it possible to explain this method in a simple and complete way? -
Django: Update method creates a new image instead or replacing the actual image
I am trying to update the car image but my form saves a new image, instead of replacing the link of the actual image. class CarUpdateForm(ModelForm): image = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Car exclude = ['id', 'created'] widgets = { 'number': widgets.NumberInput(attrs={'class': 'form-control'}), 'description': widgets.TextInput(attrs={'class': 'form-control'}), 'driven': widgets.NumberInput(attrs={'class': 'form-control'}), 'category': widgets.NumberInput(attrs={'class': 'form-control'}), 'price': widgets.NumberInput(attrs={'class': 'form-control'}), } I am not so sure at the car_image if that creates a new image instance and saves as new. @login_required def update_car(request, id): instance = get_object_or_404(Car, pk=id) if request.method == 'POST': form = CarUpdateForm(data=request.POST, instance=instance) car_image = CarImage(image=request.POST['image'], car=instance) if form.is_valid(): car_image.save() form.save() return redirect('car_details', id=id) else: form = CarUpdateForm(instance=instance) return render(request, 'car/update_car.html', { 'form': form, 'id': id }) -
django-cms: How to create custom menu like image?
I'm new with django-cms and i want to add menu like image i post. I have read the doc but i don't know how to create my custom menu. -
TemplateDoesNotExist error after deleting folder
I originally created a login page at myproject/templates/registration/login.html. I'm very new to Django, I thought I could create multiple folders within the template file, but I ran into issues trying to do so. So, I deleted the registration folder and put ALL of the templates in myproject/templates. However, now, no matter what I do, when I try to go to login.html, I get the TemplateDoesNotExist area because Django is still trying to go to registration/login.html. How do I get it to stop doing this? I do not want to add the registration folder back unless I can do multiple folders in templates. I tried having all the templates in myproject/templates to no avail. I tried myproject/myapp/templates/login.html and that doesn't work either. I tried deleting and recreating the file as well. INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] -
Copying Django Templates from an App to Main Project
I am currently building a site in which I will use several 3rd party apps among which is the aldryn_forms. To make it work successfully, I need to edit some templates. It appears that to do so, I better copy the app's templates into the main project's /templates/ directory. This way, it will override the new templates whenever I move the code to the server and re-install the apps using pip install -r requirements.txt. Is my thinking here correct? Is this a good practice that in-line with best practice for Django development? Are there some examples where this may not be a good idea? -
How to display post name on new_comment page
i would like to know how i can display the name of a post at my comment_new page: views.py def comment_new(request, pk): if request.method == "POST": form = CommentForm(request.POST) post = get_object_or_404(Post, pk=pk) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.published_date = timezone.now() comment.post = post comment.save() messages.success(request, 'You have successfully provided a comment for this Post.') return redirect('post_detail', pk=comment.post.pk) else: form = CommentForm(request.POST) return render(request, 'app/comment_new.html', {'form': form}) else: form = CommentForm() return render(request, 'app/comment_new.html', {'form': form}) template.html <a>{{ post.title }}</a> thanks in Advance -
sending email from Django view
I have a web app for ordering parts and I want to include an email when the user orders a part. I am having trouble adding the email function to my function based view. I have an existing function for saving the order form data and I wanted to simply add the email function to the same view. When I try to add it directly I keep getting error messages about inconsistent white space. So I created a new email function just below the new order view but I don't know how to pass some parameters from one function to the other. This is close but when I call the New_Order function it throws an error for order_instance not defined. Views.py @login_required def New_Order(request): if request.user.userprofile.shipment_access: if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): order_instance = form.save(commit=True) order_instance.save() return Order_Email() else: form = OrderForm() return render(request, 'app/New_Order.html', {'form': form}) else: raise PermissionDenied def Order_Email(): subject = "Part Order" + order_instance.id orderNum = order_instance.id from_email = settings.EMAIL_HOST_USER to_email = ['dummyemail@gmail.com'] message = order_instance send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=message, fail_silently=False) return HttpResponseRedirect('/Orders') I'm ok with either one combined function or with two functions and passing the parameters from one to the next. … -
Django + Celery: Page loads forever with @shared_task but works with @task
I've setup Django together with Celery using SQS. To test this locally I'm executing the task in the dispatch method of my view. If I use the @task decorator everything works as expected. But If I replace this decorator with the @shared_task decorator the page loads forever and nothing happens. I don't understand where the problem is. My celery setup import os from celery import Celery from django.apps import AppConfig, apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('kiglo') app.config_from_object('django.conf:settings', namespace='CELERY') class CeleryConfig(AppConfig): name = 'kiglo.celery' def ready(self): installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscover_tasks(lambda: installed_apps, force=True) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) Settings INSTALLED_APPS += ['kiglo.celery.celery.CeleryConfig'] CELERY_BROKER_URL = 'sqs://{aws_access_key}:{aws_secret_key}@'.format( aws_access_key=quote(get_env_variable('CELERY_AWS_ACCESS_KEY'), safe=''), aws_secret_key=quote(get_env_variable('CELERY_AWS_SECRET_KEY'), safe=''), ) CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-central-1', 'visibility_timeout': 60, # 1 minutes 'polling_interval': 5, # 5 seconds 'queue_name_prefix': 'celery-', } CELERY_RESULT_BACKEND = None # There is no result backend for SQS CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYD_TASK_TIME_LIMIT = 5 * 60 CELERYD_TASK_SOFT_TIME_LIMIT = 60 My task from celery import shared_task @shared_task def hello_world(): return "hello world" Execute the task from django.shortcuts import render from ..core.tasks import hello_world def home(request): hello_world.delay() return render(request, 'home.html') -
urllib3 HTTPError [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC]
I have some problem with my code. when I call a telegram API sometimes I get this error: ERROR: urllib3 HTTPError [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2305) I'm using django-telegrambot version 1.0.1 and python-telegram-bot version 11.1.0 anyone can help? -
Placeholder in Django for login AuthenticationForm doesn't show up
I'm creating a login form in Django using AuthenticationForm. I want to add placeholders for username and password fields. The placeholder attribute doesn't work. That doesn't make sense since I have a similar signup form, where everything shows up correctly. class UserSignUpForm(UserCreationForm): username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'nickname'})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': 'e-mail'})) password1 = forms.CharField(max_length=100, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'password'})) password2 = forms.CharField(max_length=100, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'password again'})) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') exclude = [] class UserLoginForm(AuthenticationForm): username = forms.CharField(max_length=100, widget=forms.widgets.TextInput(attrs={'placeholder': 'nickname'})) password = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'password'})) class Meta: model = AuthenticationForm AuthenticationFormFields = ('username', 'password') exclude = [] -
Model order based on a different model
In Django, I have two models; Model B has a primary key OneToOneField relationship with the primary key of model A. class A(models.Model): id = models.AutoField(primary_key=True) id2 = models.ForeignKey(also a autofield to the field it’s referencing) class Meta: ordering = [“-id2” , “id”] class B(models.Model): id = models.OneToOneField(A, primary_key=True) class Meta: ordering = [???] Is there a way for me to order model B based on Model A’s ordering without replicating data? -
Filters not following on pagination in Django
I'm trying to set up pagination within my Django project but I can't find a way to make the filters (ptags in my case) follow to the next pages. Ps; I use Django-haystack with faceting for filtering. I have a custom forms.py from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs That I pass in my Views: class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 3 context_object_name = 'object_list' Here's my full search_result.html: <div> {% if page_obj.object_list %} <ol class="row top20" id="my_list"> {% for result in page_obj.object_list %} <li class="list_item"> <div class="showcase col-sm-6 col-md-4"> <div class="matching_score"></div> <a href="{{ result.object.get_absolute_url }}"> <h3>{{result.object.title}}</h3> <h5>{{ result.object.destination }}</h5> <img src="{{ result.object.image }}" class="img-responsive"> </a> <div class="text-center textio"> <ul class="tagslist"> <li class="listi"> {% for tags in result.object.ptags.names %} <span class="label label-info"># {{ tags }}</span> {% endfor %} </li> </ul> </div> </div> </li> {% endfor %} </ol> </div> I'm able to … -
How to keep a document available for x time in a website?
I am trying to show a report for 1 hour for everyone to view it. After that I want to show the next document available for 1 hour again. The problem is 2 employees can upload the reports at the same time. which means i have to create a queue? If I show the first one after an hour it should go to the other one. But I can see the problem of 2 reports at the same timestamp. meaning that when I return the reports that has a timestamp within the last hour reports with the same timestamp will not appear. -
Running a function through a submit button
I have the following code which runs a function, at the moment the function runs when the webpage is loaded, I need the function to run when the form is submitted. It's a temporary fix which will work for now. Is a form the best way to handle this, I'm open to suggestions. Should I use javascript in some way? <form class="" action="." method="post"> {% csrf_token %} {% function1 %} <button type="submit" class="save btn btn-default">Run</button> </form> -
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 --> in python3.7.1 and ubuntu 19.04
sudo apt-get install python3.7-dev sudo apt-get install python-dev but does not work: https://stackoverflow.com/questions/35048582/how-to-fix-error-command-x86-64-linux-gnu-gcc-failed-with-exit-status-1 Compile failed: command 'x86_64-linux-gnu-gcc' failed with exit status 1 creating tmp cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitfuvqfw8a.c -o tmp/xmlXPathInitfuvqfw8a.o /tmp/xmlXPathInitfuvqfw8a.c:2:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main (int argc, char **argv) { ^~~~ cc tmp/xmlXPathInitfuvqfw8a.o -lxml2 -o a.out error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for lxml Running setup.py clean for lxml Building wheel for numpy (setup.py) ... I'm very try but i can not solve problem hellp me thanks -
static seeded random.seed() returns mixed results from loaded JS, but expected results in console, and from Postman
I am running a server on Django, one function takes a seed through a URL param GET request, generates some data based on that seed, and sends it back. The URL format: mysite.com/api/generate/<seed> expected result: submitting a GET on mysite.com/api/generate/99 gets picked up in Django as a seed value of 99. data returned is chosen with random.choice() seeding with random.seed(99) from a database which contains a single column of names. data returned is the following: Walker Lewis Dalia Aguilar Meghan Ford Theresa Hughes Kenna Coffey Kendra Ho problem Here's where I'm getting confused (code below for each): 1000 requests in postman, all 1000 return perfectly equal approx 100 requests from the google chrome console, all are equal from the generate.js that the server sends with index.html, making the same call, results degenerate (examples below) Postman call very simple, GET mysite.com/api/generate/99 jquery from chrome console $.ajax({ url: "/api/generate/99", success: function( result ) { console.log(result.data) }}) jquery from generate.js $.ajax({ url: "/api/generate/99", success: function( result ) { var data = result.data; // data is now passed about the script, but debugging at the line above shows that data has already started to vary on a request by request basis Both Postman and … -
Display JsonResponse data in template
I want to send the JsonResponse data in the demo.html and display in it. what is wrong in my code. please help me to solve it. function ComAction() { let xhr = new XMLHttpRequest(), data = new FormData(); data.append('csrfmiddlewaretoken', getCookie('csrftoken')); brands.forEach(function (brand) { data.append('brand', brand); }); xhr.open('POST', 'compare_in/', true); xhr.onload = function () { if (xhr.status === 200) { data = JSON.parse(xhr.responseText); console.log(data); alert('Data received successfully. Brands are ' + data.brands); window.location.assign({% url 'demo' %}); } else if (xhr.status !== 200) { alert('Request failed.'); } }; xhr.send(data); } it's my urls: urlpatterns = [ path('compare_in/', views.compare, name='compare'), path('demo/', views.demo, name='demo'), ] it's my views: def compare(request): if request.method == 'POST': compare_res = request.POST.getlist('brand') d3 = {'brand':{'x', 'y'}, 'color':{'black', 'white'}} response_data = { 'brands': d3, 'redirect_url': 'http://127.0.0.1:8000/demo/'} return JsonResponse(response_data) return render(request, 'prodcutSearch/compare_in.html') def demo(request): return render(request, 'prodcutSearch/demo.html') -
How to further customize the editable list display in Django Admin?
I am trying to customize the admin panel. I am displaying an editable list for bulk editing. How can I increase the width of the text boxes so I can read the full sentence without scrolling left to right and vice versa. Can anyone help? Here is my code for admin.py and a picture to make my point clear: from django.contrib import admin from . models import Sentence @admin.register(Sentence) class PostAdmin(admin.ModelAdmin): list_display = ('sent_correct',) list_editable = ('sent_correct',) list_display_links = None list_filter = ('author', 'pub_date') raw_id_fields = ('author',) search_fields = ['sent_correct'] date_hierarchy = 'pub_date' https://imgur.com/TTUSt6n -
how to recieve email from contact form in django
here i am trying to recieve email message from common users and as well as saving the message in the admin page using the contact form.This code saves the data in the admin page as i wanted but it is not taking user's email to send the message from contact form instead it is taking the configured email form settings.py .**how can user send email message to the admin gmail inbox from this contact form?**From this code email message sent to the the admin gmail inbox but the email address recieved in admin gmail inbox is the email which is configured in the settings.py views.py if request.method == 'POST': form = SendMessageForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(name, message, email, ['admin mail address']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('index') else: return HttpResponse(form.errors) else: form = SendMessageForm() settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "email" EMAIL_HOST_PASSWORD = 'pass' EMAIL_PORT = '587' template <form method="post" class="volunter-form"> {% csrf_token %} <div class="form-group"> <input type="text" name="name" class="form-control" placeholder="Your Name"> </div> <div class="form-group"> <input type="text" name="email" class="form-control" placeholder="Your Email"> </div> <div class="form-group"> <textarea name="message" id="" cols="30" rows="3" class="form-control" placeholder="Message"></textarea> </div> <div … -
Cookies when using separate Dyno for react frontend and Django backend
I am building a simple web app using React.js for the frontend and Django for the server side. Thus frontend.herokuapp.com and backend.herokuapp.com. When I attempt to make calls to my API through the react app the cookie that was received from the API is not sent with the requests. I had expected that I would be able to support this configuration without having to do anything special since all server-side requests would (I thought) be made by the JS client app directly to the backend process with their authentication cookies attached. In an attempt to find a solution that I thought would work I attempted to set SESSION_COOKIE_DOMAIN = "herokuapp.com" Which while less than ideal (as herokuapp.com is a vast domain) in Production would seem to be quite safe as they would then be on api.myapp.com and www.myapp.com. However, with this value set in settings.py I get an AuthStateMissing when hitting my /oauth/complete/linkedin-oauth2/ endpoint. Searching google for AuthStateMissing SESSION_COOKIE_DOMAIN yields one solitary result which implies that the issue was reported as a bug in Django social auth and has since been closed without further commentary. Any light anyone could throw would be very much appreciated.