Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url with IP address
I want to make this URL pattern works : http://myapp.com/api/ipaddress/username where IP address is an IPv4 and username is the account of a django user. What is the good regex format to do this at url.py ? urlpatterns = [ url(r'^$', view_api, name='api'), url(r'^(?P<ip>[0-9.])/(?P<username>\w+)/$', view_ip_check_user, name='ip_check_user'), ] -
TTF Error: Can not open a font file. Django Project
I'm running a django project, after trying to convet an HTML page to pdf, I face with this error: Exception Type: TTFError Exception Value: Can't open file "....../fonts/arial.ttf" I also tried to copy arial.ttf in usr/share/fonts and home/.font but none of them works. It may help that know I am running ubuntu from windows linux bash. can anyone help me to solve this issue? -
Installing mysql client in django virtual environment
I have created a virtual environment,with python 3 and installed django I cant install mysqlclient ,it says problem with setup.py jayanthi@jayanthi-Aspire-4920:~$ source env/bin/activate (env) jayanthi@jayanthi-Aspire-4920:~$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-4pbezvx6/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-4pbezvx6/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-4pbezvx6/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4pbezvx6/mysqlclient/ -
Don't find manage.py file in django project
I download django app from github but cant find manage.py file the app link is 1 it don't even have settings file so that I do some edit in INSTALLED_APPS PLEASE HELP -
How to use correctly plugin facebook comments?
I am developping a website for my university congress. The django website is already working, is called www.confiam.com.br, but now I am trying to add facebook comment plugin. As you can see, in the pages has many posts, I would like to add a facebook comment to each post, but I can't. If I comment in one post, all others posts receive this comment to. I am running locally, because the website is already in use. base.html ... <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.10&appId=106788150014600"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> and post_detail.html <div class=item> <p><h1>{{ post.nome_patrocinio }}</h1></p> <center><picture>{% cloudinary post.foto_patrocinio %}</picture></center> <p><h2>{{ post.apresentacao_patrocinio }}</h2></p> <div class="fb-comments" data-href= "{{ post.patrocinio }}" data-numposts="5"></div> <br> </div> I didn't add a facebook comments plugin to website online yet, only locally. I don't know if it is necessary, but in my models I don't have a slug field. Thanks very much. See you later. -
Django user model where superusers have a display name but not not normal users
I'm trying to create a custom django model where normal Users have to signup using a first name, last name, email and password but superusers must have another field called display name. However, I do not want my normal users to be able to have a display name. I'm having a little trouble implementing this though. Here's how my model looks from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password, display_name=None): user = self.model( first_name= first_name, last_name = last_name, email = email, display_name = display_name ) user.set_password(password) user.save() return user def create_superuser(self, first_name, last_name, email, password, display_name): user = self.create_user( first_name = first_name, last_name = last_name, email = email, password = password, display_name = display_name ) user.is_staff = True user.is_admin = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) display_name = models.CharField(unique=True, max_length=255) date_joined = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "display_name"] def __str__(self): return self.email def get_short_name(self): return self.email def get_long_name(self): return ("{} {} - {}".format(self.first_name, self.last_name, self.email)) The problem … -
Error reading image file
I am developing web server with Django, but I have a problem reading image files. When I receive a photo (in base64), in the first place I decode body request in utf-8 body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) data = body After I decode image and save this imgBase64 is a string with my base64 code. imgBase64 = data['FileName'] with open(path, "wb") as fh: fh.write(imgBase64.decode('base64')) At this moment I see the saved images correctly, I see each stored file well But when I try read these file, I receive an error Intent: with open("./"+str(ix.idSTFolio.path_img), "rb") as image_file: encoded_string = image_file.read() ix.idSTFolio.path_img = encoded_string UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte I don't know I can't read my files. -
Form not generating/form is_valid = 0 for radio input forms
I am writing a survey made with radio inputs. In CMD every click on the radio inputs would result on request = POST, however the form.is_valid is false since not all required buttons are pressed. I have changed it now nothing works, it won't even request now. Below is my code: models.py class Intro(models.Model): EDUCATION_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('G','Graduate'), ('P','Professor') ) SEX_CHOICES = ( ('M','Male'), ('F','Female'), ) name = models.CharField(max_length = 10) education = models.CharField(max_length = 1,choices = EDUCATION_CHOICES) sex = models.CharField( max_length = 1, choices = SEX_CHOICES) views.py def get_User_Info(request): #form_class = introForm(request.POST) if request.method == 'POST': if form_class.is_valid(): name = request.POST['name'] print(name) sex = request.POST['sex'] education = request.POST['education'] intro.objects.create( name = name, sex = sex, education = education ) intro.save() print (connection.queries) return HttpResponseRedirect("/vote/") #Save data and redirect else: form = introForm() return render(request, 'Intro.html', {'introForm': form}) Intro.html # Wrote hastily since form can't render itself for some reason... <!-- Survey/templates/Intro.html --> <!DOCTYPE html> {% load staticfiles %} <html> <body> <form action="" method="post" id = "introForm"> <p><label for="name">Name:</label> <input id=name type="text" name="subject" maxlength="15" required /></p> <p><label for="sex">Sex:</label> <input type="radio" name="Sex" value="M" required>Male <input type="radio" name="Sex" value="F" required>Female</p> <p><label for="education">Education:</label> <input type="radio" name="Education" value="1" required>1 <input … -
Getting a syntax error on a system generated file while working with django! How to fix it?
While I am setting up a supeuser in my django project using the command $ python manage.py syncdb File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax manage.py is a system generated file still it shows a syntax error. Here is the manage.py file! - !/usr/bin/env python import os import sys if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_django15_project.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) Please tell some solution! -
Static files in django(CSS)
Trying to figure out why my css won't load. -
PermissionError at / in heroku and pythonanywhere
I have been trying to deploy my django app on heroku and pythonanywhere. But I am getting the same error "PermissionError at /" and "[Errno 13] Permission denied" in both heroku and pythonanywhere. .Traceback shows lines like "from . import views ", "from .ucvt import * ","url(r'^p/', include('blog.urls')), ".It is working fine on my local machine,Please help. -
How to obtain all related objects in the second level of one-to-many relationship hierarchy?
Let's say I have three models bound in one-to-many relationship like this: class Highest(Model): pass class Medium(Model): higher = ForeignKey(Highest, on_delete=CASCADE) class Lowest(Model): higher = ForeignKey(Medium, on_delete_CASCADE) Now if I have an instance of Highest called highest I can easily obtain all related Medium objects this way: highest.medium_set.all() And if I have an instance of Medium called medium I can easily obtain all related Lowest objects this way: medium.lowest_set.all() But how do I obtain all Lowest objects that are related to any Medium object that is related to a particular Highest object? This doesn't work: highest.medium_set.lowest_set.all() I can always do this: Lowest.objects.filter(higher__higher=highest).distinct().all() But is this the only way? Or can I do it more straightforward? That is, by obtaining all related Lowest objects from a Highest object rather than filtering through all Lowest objects? -
setting up nginx with django and php [on hold]
As I have never configured any server I apologize in advance for unintentedly wrong terminology or obvious mistakes. I am trying to set up nginx for django app and php on Linux AMI (AWS). Nginx has already been configured to work for multiple django apps simultaneously and all works fine. Now I need to include the third party solution based on php. This should work on url /dash/. I went through many tutorials. This: How can I configure nginx to serve a Django app and a Wordpress site? was probably the closest match, but it did not work for me. I have already installed php and php-fpm. I modified config file at /etc/php-fpm-5.5.d/www.conf and tried using both socket and TCP/IP: listen = 127.0.0.1:9000 and also listen = /var/run/php-fpm.sock I modified nginx accordingly: location ~ /dash/$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; #fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; include fastcgi_params; } I created the test php file and also placed the third party solution to the /usr/share/nginx/html/. When I try to visit https://DOMAIN/dash/ I got 404 error (or I got blank page if I remove try_files setting). However, when I try to visit https://DOMAIN/dash/index.php or https://DOMAIN/test.php, the browser offers me a … -
How to create two different register forms for two different type of users with Django
I'm working on a project which allows business to add their local store based on their location. There is a register form for businesses which has been created extending the user model and uses email for account verification. So far, this functionality works really well. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User) activated_key = models.CharField(max_length=120, null=True) activated = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def send_activation_email(self): if not self.activated: self.activated_key = code_generator() self.save() path_ = reverse('activate', kwargs={'code': self.activated_key}) subject = 'Activa tu cuenta :)' from_email = settings.DEFAULT_FROM_EMAIL message = 'Activa tu cuenta haciendo click aquí' + path_ recipient_list = [self.user.email] html_message = '<h1>Activa tu cuenta haciendo click <a href="{path_}"aquí</a>.</h1>'.format(path_=path_) print(html_message) sent_mail = False return sent_mail def post_save_user_receiver(sender, instance, created, *args, **kwargs): if created: profile, is_created = Profile.objects.get_or_create(user=instance) post_save.connect(post_save_user_receiver, sender=User) And here my model for businesses: class Business(models.Model): owner = models.OneToOneField(User, null=False) name = models.CharField(max_length=75) logo = models.ImageField(null=True, blank=False, upload_to=upload_location) Here is my RegistrationForm on form.py: class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email',) def clean_email(self): email = self.cleaned_data.get('email') qs = … -
Django where to put the shared models and logic
I Have the following folder setup: myproject web worker The web project is a website containing the typical django setup and all, including the model and some service classes which move the logic away from the views. The website will display data coming from a database. The worker folder contains 2 classes which are filling the database and aggregate it. These 2 classes are like background processes. My question is, how should I structure this? Should each worker class get his own application folder If so, I would prefer to move the models out of the web project in the myproject folder, since they are shared between the applications. However this seems to be against the django convention, why so? And how would the convention handle this? If not, where should I put these worker processes? And how should I run them ? Thanks in advance! -
Django email: Client does not have permission to send as this sender
I am able to send emails via smtplib by using the function provided in this SO answer: https://stackoverflow.com/a/12424439/614770 from __future__ import print_function def send_email(user, pwd, recipient, subject, body): import smtplib FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ', '.join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP('smtp.office365.com', 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print('Successfully sent the mail') except: print('Failed to send mail') if __name__ == '__main__': send_email( 'my@email.com', 'password', 'my@email.com', 'Test Email', 'Can you see this?') However, I receive the following error when I try to send email via django: settings.py # Email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@email.com' EMAIL_HOST_PASSWORD = 'password' Command line python manage.py sendtestemail my@email.com smtplib.SMTPDataError: (550, b'5.7.60 SMTP; Client does not have permissions to send as this sender [BY1PR0501MB1112.namprd05.prod.outlook.com]') Have I misconfigured something in django? -
django admin, displaying all instances of a model1 associated with model2 on model2's change page?
Consider these two models Keyword and Statement (model1 and model2 respectively): @python_2_unicode_compatible class Keyword(models.Model): word = models.CharField(max_length=200) statement = models.ManyToManyField(Statement) def __str__(self): return self.word @python_2_unicode_compatible class Statement(models.Model): statement_id = models.CharField(max_length=200) title = models.CharField(max_length=200) issue_date = models.DateField("Issue-Date") author = models.ForeignKey(Person) released_by = models.ForeignKey(Organization) kicpairs = models.ManyToManyField('KeywordInContext') So on the admin site right now, the only way one would be able to determine what keywords are associated with each statement is that they have to go check the Keyword model in admin, and check each Keyword's display page and scroll through the menu. At least with regards to the admin site, it's important for someone to be able to see a Statement model's display with all of its associated Keywords visible, and for users to be able to choose additional Keywords within the database (or make new ones). I also hope to be able to have a Statement's keywords modifiable on the admin page via the filter_horizontal widget, since that seems to be the most user friendly. But I'm having trouble just starting with that. I'm not sure what I need to use or how. -
Weird template rendering behavior with Django and links <a>
I noticed that when i input a link into for loop in my templates that it gets injected into the first, lower elements. Il illustrate it below: Base template: <html> <head></head> <body> {% block content %} {% endblock %} </body> </html> template which extends Base template {% extends 'base.html'%} {% block content %} {% if elem_list %} <ul> {for elem in elem_list} <li> <a class="bob" href=""> <div class="div1"> <div class="subdiv"></div> </div> <div class="div2"> <div class="subdiv"></div> </div> </a> </li> {% endfor %} </ul> {% endif %} {% endblock %} and the output i get on my page <html> <head></head> <body> <ul> <a class="bob" href=""> <li> <a class="bob" href=""> <div class="div1"> <a class="bob" href=""></a> <div class="subdiv"><a class="bob" href=""></a></div> <div class="subdiv"></div> </div> <div class="div2"> <a class="bob" href=""></a> <div class="subdiv"><a class="bob" href=""></a></div> <div class="subdiv"></div> </div> </a></li> </ul> </body> </html> Is this some kind of feature Django has? How can i stop it? -
AttributeError: type object 'Listing' has no attribute 'object' [on hold]
Everything on the app works except for this. I can go to my form page and add a new listing. I just can't get them to display on my index page and this is the error it's giving me. -
Send placed orders to a custom email address
I am trying to send an email to a specific address (xxxxx@gmail.com) after every successful order placed. I intend to capture the signal that was fired and send the email based off those details. I forked the order app and this is from the order model from django.db import models from oscar.apps.order.signals import order_placed from django.core.mail import send_mail from oscar.apps.checkout.signals import post_checkout from oscar.apps.order.abstract_models import AbstractOrder class Order(AbstractOrder): def send_order_request(sender, **kwargs): order = kwargs['instance'] subject = 'New order placed' send_mail(subject, order, ['xxxxx@gmail.com']) order_placed.connect(send_order_request, order=self.order, user=self.user) from oscar.apps.order.models import * Im currently getting an error that says self is not defined. Is this the correct way to approach this problem? -
Can run process from another .py file
I am trying to create a class and call (multiprocess) its function. I am calling it from another file - and it fails... MyDummyClass.py: import multiprocessing class MyDummyClass: def __init__(self): print("I am in '__init__()'") if __name__ == 'MyDummyClass': p = multiprocessing.Process(target=self.foo()) p.start() def foo(self): print("Hello from foo()") example.py: from MyDummyClass import MyDummyClass dummy = MyDummyClass() When I run example.py, I am getting this error: I am in '__init__()' Hello from foo() I am in '__init__()' Hello from foo() Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Python\lib\multiprocessing\spawn.py", line 114, in _main prepare(preparation_data) File "C:\Python\lib\multiprocessing\spawn.py", line 225, in prepare _fixup_main_from_path(data['init_main_from_path']) File "C:\Python\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path run_name="__mp_main__") File "C:\Python\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "C:\Python\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Python\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "E:\Dropbox\Docs\Business\_NZTrackAlerts\Website\Current dev\NZtracker\cgi-bin\example1.py", line 2, in <module> dummy = MyDummyClass() File "...path to my file...\MyDummyClass.py", line 13, in __init__ p.start() File "C:\Python\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Python\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Python\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Python\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) File … -
django models Values error preventing me from creating a model with fields specified as parameters?e
I don't seem to understand this error or how to fix it. There's something I don't understand about django models. Consider what happens when I try to perform get_or_create on the Keyword model. Here's the model, alongside some code I write in shell. @python_2_unicode_compatible class Keyword(models.Model): word = models.CharField(max_length=200) statement = models.ManyToManyField(Statement) def __str__(self): return self.word >>> from gtr_site.models import * >>> a = Statement() >>> Keyword.objects.get_or_create(word="Testkeyword", statement=a) Traceback (most recent call last): ... ValueError: "<Keyword: Testkeyword>" needs to have a value for field "keyword" before this many-to-many relationship can be used. But if you simply write Keyword.objects.get_or_create(word="TestKeyWord") (so if you exclude the statement instance entirely), then the error disappears. I really don't understand how this error can be occurring because... Neither the Statement model nor the Keyword model actually have a field called "keyword." However, the Statement model does have a lot of components. Here's the code for it. @python_2_unicode_compatible class Statement(models.Model): statement_id = models.CharField(max_length=200) title = models.CharField(max_length=200) issue_date = models.DateField("Issue-Date") author = models.ForeignKey(Person) released_by = models.ForeignKey(Organization) keywords = models.ManyToManyField('KeywordInContext') solokeywords = models.ManyToManyField('Keyword', related_name='statement_keywords') There's three more choice fields in the model that I chose to exclude for the sake of clarity. There's only one field in the Statements … -
Add additional field in user model using django-custom-user
I am using this code https://github.com/jcugat/django-custom-user to login with email address. However, I wish to add contact number, first name and last name with the procedure it stated under Extending EmailUser model I have added contact_number under class below in model.py class MyCustomEmailUserAdmin(EmailUserAdmin): """ You can customize the interface of your model here. """ contact_number = 'contact_number I leave the class MyCustomEmailUserAdmin blank in admin.py class MyCustomEmailUserAdmin(EmailUserAdmin): """ You can customize the interface of your model here. """ pass When I log into the admin panel, under the Users, I only see email address, enter password and reenter password in the form to add user. I don't see contact number is there, any idea how should I proceed? -
how to get the key value of a dictionary in django template
i have a dictionary of list of dictionary in my view.py ... data = {'item':[{'key1':'value' ,'key2':'value2' ,'key3':'value3'}]} ... in my template i want to get the value of the key of the item dictionry, i can get the elements in the item dictionary. but how can i get the key value of the elements of my item dictionary in a for loop in my templatelike this: {% for items in item %} <li>{{item|first}}</li> {% endfor %} -
Module Not Found Error: No module named 'listings.settings'
Just starting out with Python and Django. I built this app that is basically a really simple real estate listing website. Everything is coded out and based on a tutorial I just went through, as far as I can tell everything matches. I've gotten this to work before so I'm a little confused as to what is going on. Here are two images of the error I'm getting and my file structure.