Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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/ -
inserting data into django db issues
I have the below code, trying to insert form data into the DB. I don't get an error, but nothing inserts, can anyone advise me as to why? Thanks VIEW from .models import Todo def create_task(request): if request.method == 'POST': creator = request.user assignee = request.POST.get('assignee') task = request.POST.get('task') i = Todo.objects.create(creator=creator, assignee=assignee, text=task, complete='FALSE') i.save(force_insert = True) MODEL class Todo(models.Model): creator = models.CharField(max_length=400, default="none") text = models.CharField(max_length=400) complete = models.BooleanField(default=False) assignee = models.CharField(max_length=400, default="none") def __str__(self): return self.text URLs urlpatterns = [ url(r'^$', views.todo, name='index'), url(r'^$', views.create_task, name='index'), -
How can I get different fields in a form inside a JSONField?
I'm working on a web that needs to store data that can be changed inside a JSONField. For example, my default JSON would be something like: { "apple": [ [5,10], [20,40] ], "banana": [ [5,10], [20,40] ], "orange": [ [5,10], [20,40] ], } Then my model would be something along the lines of: from jsonfield import JSONField ... class MyModel(models.Model): name = models.CharField(...) fruits = JSONField(default=json) And the form that I currently have is: class MyForm(forms.ModelForm): class Meta: model = models.MyModel fields = ( 'name', 'fruits' ) The template is a little bit trickier but lets say I have a code that prints a textbox for every number in the JSON, like: {% for fruit, values in user.MyModel.fruits.items %} <input type="text" name="{{fruit}}_0_0" value="{{values.0.0}} id="id_{{fruit}}_0_0"> <input type="text" name="{{fruit}}_0_1" value="{{values.0.1}} id="id_{{fruit}}_0_1"> <input type="text" name="{{fruit}}_1_0" value="{{values.1.0}} id="id_{{fruit}}_1_0"> <input type="text" name="{{fruit}}_1_1" value="{{values.1.1}} id="id_{{fruit}}_1_1"> I haven't been able to change the values in the database. It doesen't show an error, it just doesn't work. The MyForm.is_valid() in the views file returns False -
Using django admin site's multiple choice field
I guess most of you have paid attention to the admin site's multiple choice field: I want the exact same widget to my MultipleChoiceField in my form. How is it possible to use that widget? -
Unable to print all rows of DB to Django template
I am very new with Django and really need some help. So, I am making the basic to-do application and have created the database, added some sample data (which I can see through the admin interface) and now I need to print each line to the screen. I have the below and I'm not getting any errors, but it doesn't print. Can anyone advise? MODELS from __future__ import unicode_literals from django.db import models # Create your models here. class Todo(models.Model): text = models.CharField(max_length=400) complete = models.BooleanField(default=False) def __str__(self): return self.text VIEWS from .models import Todo def todo(request): todo_list = Todo.objects.all() context = {'todo_list' : todo_list} return render(request, 'home.html', context) HOME.HTML <ul> {% for todo in todo_list %} {{todo_list}} <li>{{ todo.text }}</li> {% endfor %} </ul> URLS from django.conf.urls import include, url from django.contrib import admin from netshock import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), url('login/', views.login_user, name='login'), url('logout/', views.logout_user, name='logout'), ] SETTINGS TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/django/django_project/netshock/templates/authenticate'], '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', ], }, }, ] -
Django celery, celery-beat: fills the queue without control, scheduling troubles
I have small project with couple of tasks to run several times a day. The project is based on Django 2.1, having celery 4.2.1 and django-celery-beat 1.3.0. And also have rabbitmq installed. Each task is inside it's projects application. Runs, works, gives some result. The problem is - on virtual server, leased from some provider, if I set any task to run periodically (each hour, or two)- it starts running immidiately, without end and, as i suppose in some kind of parallel threads, wish mesh each other. Command rabbintmqctl list_queues name messages_unacknowldged always shows 8 in queue celery. Purging the queue celery does not give any changes. Restarting service - too. But setting tasks schedule to run in exact time works good. Well, almost good. Two tasks have schedule to run in the beginning of different hours (even and odd). But both run in about 30 minutes after hour beginning, of the same (odd) hour. At least tasks don't run more times in a day than set in schedule. But it is still something wrong. As a newbie with rabbitmq and celery don't know where to look for solution. Official celery docs didn't help me. May be was not looking β¦ -
How do I get my PyCharm project to recognize my locally installed psycopg2 module?
I'm using PyCharm 2018.2.4 Professional Edition, Python 3.7 and Postgres 9.5 on Mac OS X. I have set up a connection to a PostGres DB running locally in my settings.py file ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myproject', 'USER': 'myproject', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } However, when I press "Option" and "R", I get the following error File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Yet on my command line, I'm able to install the library successfully (I'm confused about whether to run pip or pip3 so I ran both): localhost:myproject_project davea$ pip install psycopg2 Collecting psycopg2 Downloading https://files.pythonhosted.org/packages/5c/c1/5e70da7f3ce144c5366e12d8b9c4d8659e803d03c8ec5057cb2eb0ee8077/psycopg2-2.7.6.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) 100% |ββββββββββββββββββββββββββββββββ| 1.5MB 110kB/s Installing collected packages: psycopg2 Successfully installed psycopg2-2.7.6.1 localhost:myproject_project davea$ pip3 install psycopg2 Collecting psycopg2 Downloading https://files.pythonhosted.org/packages/ff/db/942f8e40e93b5fe060c8d3a736d8fdd134fa5308dba8484dc06ae46e3fbd/psycopg2-2.7.6.1-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) 100% |ββββββββββββββββββββββββββββββββ| 1.5MB 441kB/s Installing collected packages: psycopg2 Successfully installed psycopg2-2.7.6.1 How do I install this module? -
when modelformset_factory and user identities disagree - a django predicament
The idea here is that each registered user should have access to posting 9 images to their profile page, and I was hoping I could use a modelformset_factory in order to keep D.R.Y. in terms om the model and the template. Several issues: I can only get one image to go through for each user that I have registered, also users can modify oneanother's images at the moment, which of course isn't optimal. The modelformset_factory form which is generated "thinks" that these 9 images are to be distributed amongst the users, ie. user pk=1 gets the first field, user pk=2 gets the second and so on and so forth. In stead I would like the factory to understand that each user should own 9 images and that only the owners of the images may modify their own galleries. I have no idea what I could put into the def __str__(self) to ensure that the images which the factory would spit out are appended with some sort of unique ID. It adds the username just fine, but it would be good if it could differentiate for instance by appendage of numbers 1 through 9 (please review comment in the model for β¦ -
AJAX Data not Posting to View in Django
I've implemented a basic checkout wherein a user may select a shipping address from a list of addresses via the 'address' class. It works on the server side, but I would like to use AJAX to avoid having the page refresh with each selection. The code is not posting any data, however. What am I doing wrong? views.py def pick_address(request): if request.method == 'POST': checkout = Checkout.objects.get(pk=request.POST.get('checkout')) checkout.shipping_address = ShippingAddress.objects.get(pk=request.POST.get('address')) checkout.save() return HttpResponse('success') pick_address.js <script> $('.address').click(function () { $.ajax({ type: 'POST', url: '{% url 'pick-address' %}', dataType:'json', data: { checkout: {{ checkout.pk }}, address: {{ address.pk }}, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { if (data['success']) { alert('success!'); } } }); }); </script> -
How to get bytes from a BinaryField in Django?
Consider we have a model with a BinaryField: from django.db import models import hashlib class Target(models.Model): # ... image = models.BinaryField(max_length=(1<<24)-1) # ... def __str__(self): return hashlib.md5().update(image).hexdigest() Does the above code computes correctly the MD5 digest of the image? Or is there some method or variable inside BinaryField to get the memory to pass to the update() method? -
Django - Order by a GenericRelation count
I have the following model: class Story(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stories') likes = GenericRelation(Like) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Like is just a simple model that uses Django's content type framework: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) target = GenericForeignKey('content_type', 'object_id') All I want to do is order my stories by most liked, but I am unable to do so. I've tried the following with no avail: stories = Story.objects.annotate(count=Count('likes')).order_by('-count') Is there an easy way of doing this? -
Using jQuery mobile page transitions with Django url redirects
I am working on a website with jQuery mobile to style it and control ajax page transitions, but I am attempting to have an external redirect from the login page to the profile page using a Django redirect in the view. However, the url comes up as localhost:8000/#profile as if it is a jQuery redirect when I want it to be an external url redirect to localhost:8000/profile. I would use rel="external" or data-ajax="false", but the redirect is from a form sent to the Django view, not an html anchor tag. My html is: <html> <head> {% load staticfiles %} <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'jquery-2.2.4.min.js' %}></script> <script src={% static 'jquery.mobile-1.4.5.min.js' %}></script> <link rel="stylesheet" href={% static "jquery.mobile-1.4.5.min.css" %}> <meta name="viewport" content="initial-scale=1"> </head> <body> <div id='login' data-role="page"> <div data-role="header"> <h1 class="title">Login</h1> <a data-transition="slide" id="to_new_account" class='ui-btn-right' href="#create_account">create</a> </div> <div data-role="content"> <form id="login_form" action="" method="POST"> {% csrf_token %} <input type="text" value="username" name="username"> <br> <input type="text" value="password" name="password"> <br> <input type="submit" value="login" name="login_button"> </form> </div> </div> <div id="create_account" data-role="page"> <div data-role="header"> <h1 class="title">new</h1> <a data-transition="slide" data-direction="reverse" class="button" href="#login">login</a> </div> <div data-role="content"> <form id="create_form" action="" method="POST"> {% csrf_token %} <input type="text" value="username" name="username"> <br> <input type="text" value="password" name="password"> <br> <input type="text" value="email" β¦ -
Partial match in Django search
Is there a way to match for example "123" to "1234" (or "myse" in "mysearch", case insensitive) when performing a Django search? -
How to allow a django end-user to create their own table in a controlled and secured way?
This is regarding: Django / Django ORM / POSTGRES Goal: Allow an end-user to inherit from an existing model, create extra fields in it or create an entirely new model. pseudo model code Example: OriginalModel name = "Main Model" Value_1 = "First Value" User created variation parent = OriginalModel name = "Custom Model" Value_1 = "First Value" Value_2 = "Custom Additional Value" I tried: test_choices = ( ('str', 'str'), ('num', 'num'), ) class App(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') name = models.CharField(max_length=100) class AppField(models.Model): app = models.ForeignKey(App, on_delete=models.CASCADE) type = models.CharField(max_length=100, choices=test_choices, null=True) title = models.CharField(max_length=100, default='') Problem How do you allow a user to create an AppItem that uses fields in AppField as model fields? Do you know a better way of doing this whole thing? -
I want to build a project with scrapy framework working as backend, Django as the framework and a UI to get the URL to scrape
I have the scrapy framework setup and running as a standalone project. What I want to build next is a Django framework, integrate that with my scrapy framework and build a UI(I know HTML/CSS) where a user can enter the URL to scrape and that URL is fetched and loaded to the backend spider script as a variable to crawl. Could someone guide me to some methodologies, or articles or answers, I just want to know the approach as to how to tackle this in the best possible way. Thanks in advance!