Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
2 django apps installed locally are not working properly on same browser, facing login/logout problem
I am working on 2 Django app which is running on ports - 8001 and 8002. But the problem is when I click on any link on the second app, the first app make me log out and when I log in to the first one, the second app makes me log out. Is there any session conflict? Can anyone suggest me how to solve this? -
Unable to see logging messages in django using the logging module
I'm a newbie to logging. I added the code for logging in my views.py file and I added the settings as per the django documentation in my settings.py file. However, the logging.txt file shows other exceptions at DEBUG level or no output at WARNING level. The website is working properly and I have it live on an EC2 instance. Here's the code for in my views.py file: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def index(request): ... logger.error("THIS IS A LOG ERROR!!!") logger.warning("THIS IS A LOG WARNING!!!") ... return render(...) Here's the code in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logging.txt', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } What am I doing wrong? -
django oauth2 creating application redirect problem
when I want to create an application with this url http://127.0.0.1:8000/o/applications/ , it always redirects me to this address http://127.0.0.1:8000/accounts/login/?next=/o/applications/ how can I solve it?, note that I don't want to use Django admin -
How to send javascript variable and form data on same time in django?
i have javascript variable and i want to sent it to django view with ajax() method here is my code. $('#orderDetails').submit(function() { // catch the form's submit event $.ajax({ type: 'POST', url: 'order/', headers: {"X-CSRFToken":'{{ csrf_token }}'}, data: { 'test': 12, } }); return false; }); here is form code <form action="{% url 'order:order_detail' %}" method="post" enctype="multipart/form-data" id="orderDetails"> {% csrf_token %} <input type="submit" value="Proceed" class="btn"> </form> and here is views.py def order_detail(request): test = request.POST.get('test') print(test) it print none.any one can help please? -
Looking for a tool for approve or reject user actions
I have a requirement in my app where user registration is to be approved or rejected. Same thing is also valid for when a user edits his/her profile. It should be approved or rejected by admin. I tried to use django-moderation but it has countless of different bugs and seems not well maintained for years. What different tool can I use for this goal? -
How to make a follow button in django?
I am trying to make a list of post which will have a follow button to follow that particular user, but for saving instance of that user, we usually uses django forms via post methods where a user fills that form. I want to make follow button like that of instagram on explore page. can i use javascript to fill the form? if yes, please elaborate. -
django-admin.py is using Django 1.11 instead of Django 2
I have both python2 and python3 installed on my ubuntu machine Also I have both versions of Django Installed whenever I make a new project in django django-admin is using Django 1.11 by default How do I create a project in Django 2 ?? -
Javascript interfering with django forms
I have an issue where somewhere in my code the javascript is interfering with the form updates. Django form not submitting or providing error messages I've also uploaded all the code on github; I've tried almost everything and I think it may be one of the 3rd party packages installed. https://github.com/lkal88/djangoproject If anyone could point me in the direction to help identify/fix the issue, it'll be awesome! -
How to fix NoReverseMatch in django
I am developing an ecommerce website just for a practice and all the codes were working fine but all of a sudden I am getting a error at the django template I have tried following most of the answers but none of it seems to working This is my urls.py urlpatterns = [ url(r'^$', views.cart_detail, name='cart_detail'), url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'), url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'), ] this is my main urls.py of the project urlpatterns = [ # Examples: # url(r'^$', 'myshop.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^cart/', include('cart.urls', namespace='cart')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^paypal/', include('paypal.standard.ipn.urls')), url(r'^payment/', include('payment.urls', namespace='payment')), url(r'^coupons/', include('coupons.urls', namespace='coupons')), url(r'^', include('shop.urls', namespace='shop')), ] this is the template in which I am getting error {% block content %} <h1>Your shopping cart</h1> <table class="cart table-striped "> <thead> <tr> <th>Image</th> <th>Product</th> <th>Quantity</th> <th>Remove</th> <th>Unit Price</th> <th>Price</th> </tr> </thead> <tbody> {% for item in cart %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %} {{ product.image.url }} {% else %}{% endif %}"> </a> </td> <td>{{product.name}}</td> <td> <form action="{% url 'cart:cart_add' product.id %}" method="post"> {{item.update_quantity_form.quantity}} {{item.update_quantity_form.update}} <input type="submit" class=" btn btn-default outline" value="update"> {% csrf_token %} </form> </td> <td> <a href="{% url 'cart:cart_remove' product.id %}">Remove</a> </td> <td class="num">${{item.price}}</td> … -
Python Django heroku error "remote rejeced"
Whenever I type command: git push heroku master Enumerating objects: 32, done. Counting objects: 100% (32/32), done. Delta compression using up to 4 threads Compressing objects: 100% (30/30), done. Writing objects: 100% (32/32), 11.43 KiB | 557.00 KiB/s, done. Total 32 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.7 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting dj-database-url==0.5.0 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl remote: Collecting Django==2.1.3 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/d1/e5/2676be45ea49cfd09a663f289376b3888accd57ff06c953297bfdee1fb08/Django-2.1.3-py3-none-any.whl (7.3MB) remote: Collecting django-heroku==0.3.1 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/59/af/5475a876c5addd5a3494db47d9f7be93cc14d3a7603542b194572791b6c6/django_heroku-0.3.1-py2.py3-none-any.whl remote: Collecting gunicorn==19.9.0 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 4)) remote: Downloading https://files.pythonhosted.org/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB) remote: Collecting psycopg2==2.7.6.1 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 5)) remote: Downloading https://files.pythonhosted.org/packages/bc/2a/61a8f9719bd6df5b421abd91740cb0595fc3c17b28eaf89fe4f144472ca6/psycopg2-2.7.6.1-cp36-cp36m-manylinux1_x86_64.whl (2.7MB) remote: Collecting pytz==2018.7 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 6)) remote: Downloading https://files.pythonhosted.org/packages/f8/0e/2365ddc010afb3d79147f1dd544e5ee24bf4ece58ab99b16fbb465ce6dc0/pytz-2018.7-py2.py3-none-any.whl (506kB) remote: Collecting whitenoise==4.1.2 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 7)) remote: Downloading https://files.pythonhosted.org/packages/fd/2a/b51377ab9826f0551da19951257d2434f46329cd6cfdf9592ea9ca5f6034/whitenoise-4.1.2-py2.py3-none-any.whl remote: Installing collected packages: dj-database-url, pytz, Django, whitenoise, psycopg2, django-heroku, gunicorn remote: Successfully installed Django-2.1.3 dj-database-url-0.5.0 django-heroku-0.3.1 gunicorn-19.9.0 psycopg2-2.7.6.1 pytz-2018.7 whitenoise-4.1.2 it give error here remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: … -
django oauth2 creating application redirect problem
when I want to create an application with this url http://127.0.0.1:8000/o/applications/ , it always redirects me to this address how can I solve it?, note that I don't want to use Django admin -
Why attribute of a dictionary works in template html through connection with codes in view.py ?
I am new to Django, and I am following a tutorial in which he writes something like {%for post in posts %} {{post.author}}in the template html file. He describes that the template responds to the key 'posts'. To my understanding, post is a dictionary according to what he writes in view.py? How does it work? posts = [ { 'author': 'JosephJ', 'title': 'Blog Post1', 'content': 'First post content', 'date_posted': 'August 27, 2018' }, { 'author': 'RogerL', 'title': 'Blog Post2', 'content': 'Second post content', 'date_posted': 'August 28, 2018' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html', context) -
ordering by descending order in django views
I am using sorted() to combine two queryset and then ordering them by DatePosted but i want to sort it in reverse order, that is, new to oldest. How can i do it? def feed(request): if request.user.is_authenticated: result_list=post.objects.none() usrpost=post.objects.none() channel_result=channel.objects.none() chnpost=channel.objects.none() userprofile=FollowingProfiles.objects.filter(Profile__user=request.user) for p in userprofile: postuser=post.objects.filter(Profile__user__username=p.ProfileName) result_list=sorted(chain(usrpost,postuser),key=operator.attrgetter('DatePosted')) usrpost=result_list result_list=usrpost postuser=post.objects.none() profile_result=Profile.objects.filter(user__username=request.user.username) -
Django - how to access a ForeignKey parent's attribute?
I'm a newbie in Django, and I don't know how to this. I have a model 'Seller': class Seller(models.Model): seller_name = models.CharField(max_length=50) def __str__(self): return self.seller_name and a model 'Item': class Item(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) item_name = models.CharField(max_length=100) item_category = models.CharField(max_length=100, choices=ALL_CATEGORIES) item_price = models.FloatField() item_preview = models.ImageField(upload_to='previews/<the seller's name>') def __str__(self): return self.item_name connected via ForeignKey to Seller. In this model, I have an ImageField, and I want it to upload the files to previews/Seller's name directory, but I don't know how to access the Seller's name from Item. Is it possible? Or am I doing something I am not supposed to? Because I couldn't find any similar cases in the internet. -
Django TypeError missing 1 required positional argument: 'listing_id'
Django newbie here. For my first project, I'm following a course that I found online which is a website for finding properties, realtors and stuff. On the landing page, I have a search form which can be used to find properties based on location, price, etc. However though, on submitting the form it gives me the following error. TypeError at /listings/search listing() missing 1 required positional argument: 'listing_id' Request Method: GET Request URL: http://localhost:8000/listings/search?keywords=&city= Django Version: 2.1.4 Exception Type: TypeError Exception Value: listing() missing 1 required positional argument: 'listing_id' Exception Location: /home/nived/Documents/BTRE_PROJECTF/venv/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 124 Python Executable: /home/nived/Documents/BTRE_PROJECTF/venv/bin/python Python Version: 3.6.7 Python Path: ['/home/nived/Documents/BTRE_PROJECTF', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/nived/Documents/BTRE_PROJECTF/venv/lib/python3.6/site-packages'] I'm not sure which listing_id is being referred to here. As of now I haven't added any markup to the search.html file. It just has a simple <h1>Search</h1> I wanted to make sure that the pages are linked properly before I begin adding more content. Index Page html <section id="showcase"> <div class="container text-center"> <div class="home-search p-5"> <div class="overlay p-5"> <h1 class="display-4 mb-4"> Property Searching Just Got So Easy </h1> <p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Recusandae quas, asperiores eveniet vel nostrum magnam voluptatum tempore! Consectetur, id commodi!</p> <div … -
Django channels or Signals?
Channels or signals for user notification. Im currently working on creating this online booking django app. I was quite new on django and im wondering what should i use to notify certain users that a new booking has been made. Do i use channels or signals? -
Select distinct pairs from a MySQL table data in Django
I am writing a logistics application that tracks various routes, I want to write code that can find all the routes in the system. For example in the following database: From | To | Time Seattle | Chicago | 12PM Chicago | Seattle | 9 AM Seattle | Chicago | 2PM Chicago | Houston | 3PM The result should be: From | To Seattle | Chicago Chicago | Houston Basically, the direction doesn't matter, only the pairs do. I tried using join statements by using djangos raw() function but this prints out all the routes multiplied by the number of times that pair appears, so in the above example it would print out the 1st, 2nd and 3rd record 3 times each as well as the last record. fls = Route.objects.raw('SELECT * ' 'FROM manager_route f1, flights_flight f2 ' 'WHERE (f1.origin_id = f2.destination_id AND f1.destination_id = f2.origin_id)' 'OR (f1.origin_id = f2.origin_id AND f1.destination_id = f2.destination_id)') -
Testing form in Django with regex validation
I have the form in Django with username field. By validation I check if there are some not Latin letters in it. Now I want to add test for this validation. Creating separate function for each wrong value looks not like best solution. What is the best way implement tests like this? Is it wrong way to do something like function below? def test_not_allowed_symbols(self): for symbol in ["!@#$%^&*()_+§±';:фй¡™£¢∞§¶•ªº–≠A"]: form_data = {'username': symbol,} form = UserCreating(data=form_data) self.assertFalse(form.is_valid()) -
Django 2.1 NOT NULL constraint when setting ForeignKey
I am setting FK to an object from a previous form submission, but I can't seem to figure out why I am getting a null constraint error. I have scoured SO and reddit for similar issues, but I think that I am missing something simple here (or I just can't wrap my brain around the FK concept). error: ... return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: reports_attendance_entry.event_id models.py class Event_Profile(models.Model): content_area = models.CharField(max_length=120) #max_length = required event_date = models.DateField(default=datetime.date.today) # Need to make this more flexible event_location = models.CharField(max_length=120) workshop_number = models.CharField(max_length=15) cost_per_person = models.DecimalField(max_digits=10,decimal_places=2) #def __str__(self): #return self.name # Create an attendance listing for an existing event class Attendance_Entry(models.Model): event = models.ForeignKey('Event_Profile', on_delete=models.CASCADE) district_name = models.CharField(max_length=120) number_registered = models.PositiveIntegerField() number_of_noshows = models.PositiveIntegerField() #def __str__(self): #return self.name forms.py # Create a new event with the below fields class New_Event_Form(forms.ModelForm): content_area = forms.ModelChoiceField( queryset=Content_Area.objects.all(), required=True) event_date = forms.DateField( label = 'Event Date', required=True, initial=datetime.datetime.today().strftime('%Y-%m-%d')) event_location = forms.ChoiceField( choices = location_list, required=True, widget = forms.RadioSelect()) workshop_number = forms.CharField( required=False) cost_per_person = forms.DecimalField( required=True, decimal_places=2, label='Cost/Person', initial="0.00") class Meta: model = Event_Profile fields = [ 'content_area', 'event_date', 'event_location', 'workshop_number', 'cost_per_person' ] # Add a district to a corresponding event and carry … -
django app is working while not included in settings.py
I am reading the tutorials for django on their site. In the first tutorial https://docs.djangoproject.com/en/2.1/intro/tutorial01/ they are creating an app called polls and a view inside, and when running the server the view is displayed. However, in the second tutorial https://docs.djangoproject.com/en/2.1/intro/tutorial02/ it is mentioned that the app should be added in the installed apps section of the settings.py To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting. I am not sure how it worked in the first tutorial without including the app. Isn't it mandatory to include the app? or is it mandatory only in specific use cases? Thank you -
Django: Create webhook receiver
I am currently trying to implement webhooks for enter link description here. I can't find much in the documentation about creating a webhook. Do you have any good repositories or pages I can look into to get a better understanding of how to build a webhook for Typeform? -
Django Email sends on console but not on webserver
Followed a number of tutorials online, contact form prints to back end console. When I upload to webserver and change EMAIL_HOST etc...this no longer sends and nothing is on the log on the server to show it's even attempted. It is with hostpresto that it's hosted I've tried using smtp.backend and also django_smtp_ssl.SSLEmailBackend neither of which have helped settings.py #Contact Form Email EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'cp163173.hpdns.net' EMAIL_HOST_USER = 'enquiries@oculus-media.co.uk' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 465 views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.contrib import messages from .forms import ContactForm, seoSearch def contacts(request): OrderType = request.POST.get('Package') if request.method =='GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() ''' End reCAPTCHA validation ''' if result['success']: subject = 'Web Enquiry' contactType = form.cleaned_data['contactType'] contactName = form.cleaned_data['contactName'] contactEmail = form.cleaned_data['contactEmail'] contactPhone = form.cleaned_data['contactPhone'] contactStart = form.cleaned_data['contactStart'] contactBudget = form.cleaned_data['contactBudget'] contactCompany = form.cleaned_data['contactCompany'] contactPhone = str(contactPhone) contactBudget = str(contactBudget) contactStart = str(contactStart) formData = "Enquiry Type - " + contactType + "\nContact Name - " + contactName … -
Check with Django if URL is in i18n_patterns
With the following, I can test if a certain URL path is in my Django roject's URL conf: from django.urls import is_valid_path, resolve url = '/test/' print is_valid_path(url) >>>> True print resolve(url) >>>> ResolvedPattern Unfortunately, when using i18n_patterns to define international URLs with language code prefix, the resolver is not returning them as valid, for example: url = '/fr/test/' # test French URL print is_valid_path(url) >>>> False print resolve(url) >>>> error Resolver404 How can I either include the localized URLs or check for those separately? Thanks! -
how to set multiple widget setting to a input box
I'd like to add multiple attribute to one input box as follows using django. I have tried the code as below in forms.py, but seems it only works for the former sentence(placeholder setting in the code below) widgets = { 'content': forms.TextInput(attrs={'placeholder': 'What are you doing today?'}), 'content': forms.Textarea(attrs={'cols': 300, 'rows': 3}), } -
Django Media URL not returning string to Media folder
Running django 2.0 in development and I am trying to display user uploaded images in a List view. Here is the line for the img tag <img class="img-responsive" src="{{MEDIA_URL }}{{ selected_membership.image }}" alt="Subscription Logo"> For testing purposes {{ MEDIA_URL }}{{ selected_membership.image }} returns "my_image.jpg". So clearly the MEDIA_URL is not working, but the second part is. Urls.py ... if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py ... PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' {{ MEDIA_URL }} Needs to return /media/