Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble installing Django: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rcF9a5/Django/
I'm trying to install Django via command prompt. I used "pip install Django" but got this message: Collecting Django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-rcF9a5/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rcF9a5/Django/ How do I fix this? -
What is the purpose of adding to IINSTALLED_APPS in Django?
Most documentation simply tells you to add the name of each of your apps to the INSTALLED_APPS array in your Django project's settings. What is the benefit/purpose of this? What different functionality will I get if I create 2 apps, but only include the name of one in my INSTALLED_APPS array? -
Trouble with nginx and django configuration?
I use NGINX+GUNICORN+DJANGO and my gunicorn status is active. I want to set up nginx with django. I create a new file named 'mysite'in /etc/nginx/sites-available server { listen 8000 default_server; listen [::]:8000 default_server; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/split/mysite; } location / { include proxy_params; proxy_pass http://unix:/home/split/mysite/mysite.sock; } } saved it and create symbolyc link to /etc/nginx/sites-enabled After that I did sudo service nginx restart and got this: Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details. I went to journalctl -xe -- -- Unit nginx.service has finished shutting down. Dec 07 01:05:17 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server... -- Subject: Unit nginx.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit nginx.service has begun starting up. Dec 07 01:05:17 ubuntu nginx[49646]: nginx: [crit] pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory) Dec 07 01:05:17 ubuntu nginx[49646]: nginx: configuration file /etc/nginx/nginx.conf test failed Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Control process exited, code=exited status=1 Dec 07 01:05:17 ubuntu sudo[49639]: pam_unix(sudo:session): session closed for user root Dec 07 01:05:17 ubuntu … -
How do I fix my mailgun to Django route "IncompleteRead" error?
Hello I'm trying to test my Mailgun route to send emails through Http Post but I keep getting this error: Post failed: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read)) Here is the sample view I'm using to handle the Post requests: def on_incoming_message(request): if request.method == 'POST': sender = request.POST.get('sender') recipient = request.POST.get('recipient') subject = request.POST.get('subject', '') body_plain = request.POST.get('body-plain', '') body_without_quotes = request.POST.get('stripped-text', '') # note: other MIME headers are also posted here... # attachments: for key in request.FILES: file = request.FILES[key] # do something with the file # Returned text is ignored but HTTP status code matters: # Mailgun wants to see 2xx, otherwise it will make another attempt in 5 minutes return HttpResponse('OK') I thought what I had to do was simply make a url to catch Http Post requests. Am I missing something extra? Post failed: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read)) -
Run python scripts from within Django app
I'm helping to build a Django app that will interface with a voip phone system, and they've created some scripts to execute when an action is performed (add, update,delete) in order to have parity with the phone system side. They've asked me to pass the parameters to the script like this /var/www/html/om/om_add.sh deviceid filename title They've also mentioned to pass the title as a url, using urllib.quote_plus(title) Lastly, it should occur after each action is executed in the app. Now, I've heard that executing shell scripts from a Django app is not advised, but wondering if this is a different case? Also, how I can go about doing this, the only way I know how to pass those params is to pass them through a view. Any help is greatly appreciated! -
django selenium test for form submit and redirect
I'm trying to do a test with selenium in django but not sure how to test that the view will put the form data in the request session and redirect correctly to the next page? (I'm also unsure how to get the session from selenium like the django client?) class MySeleniumTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() options = webdriver.ChromeOptions() options.add_argument('headless') try: cls.selenium = webdriver.Chrome(chrome_options=options) except: raise Exception("couldn't start headless client") @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_postcode_signup(self): self.selenium.get(f"{self.live_server_url}/users/postcode/") postcode_input = self.selenium.find_element_by_id('id_postcode') postcode_input.send_keys(postcode) self.selenium.find_element_by_tag_name('button').click() #self.assertRedirect() #self.selenium.session? #self.assertEqual(postcode,self.client.session.get('postcode')) -
"[Errno 12] Cannot allocate memory" on Geoip2() in Django with uWSGI
The following code runs successfully in manage.py shell: from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() If I start the server manually with manage.py runserver and put the code in my Django view, it also runs fine. My Django application is hosted with uWSGI and Nginx as reverse proxy. Both uWSGI and Nginx run with www-data user. Here is the exception that I get there: ... File "/home/myuser/Env/virtenv/myproject/index/views.py" in index 28. g = GeoIP2() File "/home/myuser/Env/virtenv/local/lib/python2.7/site-packages/django/contrib/gis/geoip2/base.py" in __init__ 95. self._city = geoip2.database.Reader(city_db, mode=cache) File "/home/myuser/Env/virtenv/local/lib/python2.7/site-packages/geoip2/database.py" in __init__ 82. self._db_reader = maxminddb.open_database(filename, mode) File "/home/myuser/Env/virtenv/local/lib/python2.7/site-packages/maxminddb/__init__.py" in open_database 37. return maxminddb.reader.Reader(database, mode) File "/home/myuser/Env/virtenv/local/lib/python2.7/site-packages/maxminddb/reader.py" in __init__ 52. db_file.fileno(), 0, access=mmap.ACCESS_READ) Exception Type: error at / Exception Value: [Errno 12] Cannot allocate memory Local variables are: Variable Value database '/home/myuser/Env/virtenv/myproject/geoip/GeoLite2-City.mmdb' db_file <closed file '/home/myuser/Env/virtenv/myproject/geoip/GeoLite2-City.mmdb', mode 'rb' at 0x7f8c5cf5d390> mode 0 self <maxminddb.reader.Reader object at 0x7f8c5cf5f550> I use Virtualbox and my guest OS is Ubuntu 16.04. I have 4GB swap file there. If I free up some RAM the problem persists. This shouldn't be a memory issue on OS level, though, as I can create the GeoIP2 object in the shell and also if I run the server manually. Next thing I checked is that … -
Django: List all where one field combines all its unique values.
I got stuck. Problem I have is that I would like to create a list of objects.all() but where all objects, where one ForeignKey is the same, should be combined to one entry in a list. My Model: class TournamentStandings(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) player_place = models.FloatField(verbose_name=u"Place") The list I would like to get is something like this: ID | Player | Tournament| Place 1 | Name_1 | Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2 2 |Name_2 |Tournament_1, Tournament_2| Place_on_tournament_1, P_o_t_2 So the ForeignKey(Player) would be the one I would like to limit and combine entries. I tried the generic view for objects.all() and the loop in my template: {% for player in ranking_list %} <tr> <td>{{ ranking_list.id }}</td> <td>{{ ranking_list.player }}</td> <td>{{ ranking_list.tournament }}</td> <td> {{ ranking_list.player_place }} </td> </tr> {% endfor %} It didn't work. Any hints ?? -
How to order Django querysets by upcoming birthdays
I want to list all users ordered by witch have their birthdays nearer. How do I order by by upcoming birthdays. -
Automatically set the primary key for one table as the foreign key for another?
I have two Django models: class seller_event(models.Model): event_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length = 300, default = 'Null') description = models.CharField(max_length = 300, default = 'Null') location = models.CharField(max_length= 300, default = 'Null') cash_payment = models.BooleanField(default=True) paytm_payment = models.BooleanField(default=False) def __unicode__(self): return str(self.event_id) class seller_event_items(models.Model): item_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(seller_event) item_name = models.CharField(max_length = 300, default = 'Null') item_price = models.CharField(max_length = 300, default = 'Null') item_quant = models.CharField(max_length = 300, default = 'Null') def __unicode__(self): return str(self.item_id) The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such: forms.py: class Seller_event(forms.ModelForm): class Meta: model = seller_event exclude = {'user'} class Seller_event_items(forms.ModelForm): class Meta: model = seller_event_items exclude = {'event_id'} views.py: def newlist(request): if request.user.is_authenticated(): user = request.user print user if request.method == 'POST': seller_event_form = Seller_event(request.POST) seller_event_items_form = Seller_event_items(request.POST) if seller_event_form.is_valid() and seller_event_items_form.is_valid(): new_seller_event = seller_event_form.save(commit=False) new_seller_event.user = user new_seller_event.save() seller_event_items_form.save() return redirect('/home') else: seller_event_form = Seller_event() seller_event_items_form = Seller_event_items() return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form}) The form here is helping a seller both create a sale and then populate the sale with … -
Django - Cannot update model with model form gives str error
Im trying to let the user update some of the settings on their team but it doesn't seem to work correctly I want to update the name and if they accept users. Views.py @login_required def teamsettings_general(request, team_pk): logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_team = get_object_or_404(Team, pk=team_pk) if request.method == 'POST': for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: form = TeamSettings_GeneralForm(request.POST, instance=team_pk) if form.is_valid(): form.save() messages.success(request, "The team has been updated!") return redirect('teamsettings_general', team_pk=team_pk) for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: feedback = FeedbackSupportForm() form = TeamSettings_GeneralForm(instance=team_pk) context = { 'requested_team': requested_team, 'feedback': feedback, 'form' : form, 'logged_in_user': logged_in_user, } return render(request, 'team/settings.html', context) break else: return redirect('team', team_pk) and my form.py class TeamSettings_GeneralForm(forms.ModelForm): class Meta: model = Team fields = ('name', 'accepts_applications',) Now I just want it to update name and accepts_applications 'str' object has no attribute '_meta' form = TeamSettings_GeneralForm(request.POST, instance=team_pk) if form.is_valid(): form.save() messages.success(request, "The team has been updated!") return redirect('teamsettings_general', team_pk=team_pk) logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_team = get_object_or_404(Team, pk=team_pk) form = TeamSettings_GeneralForm(instance=team_pk) ... for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: feedback = FeedbackSupportForm() context = { 'requested_team': requested_team, 'feedback': feedback, Thanks in adbanvce -
Force SSL for Django Postgres connection
I want to force Django to use SSL to connect to my postgres database. This question indicates that I need to pass sslmode='require' to the psycopg2 connect call. How do I add this to Django's database paremeters? -
AttributeError: 'tuple' object has no attribute 'get' Django Rest-Auth
I am trying to override the django-rest-auth RegisterSerializer. in settings file I have: # for use with the custom signup serializer REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'myapp.users.serializers.CustomRegisterSerializer' }, in the serializers I have also have the customserializer class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField(required=True, write_only=True) last_name = serializers.CharField(required=True, write_only=True) ... def save(): ... app name in in appconfig class UsersConfig(AppConfig): name = 'myapp.users' verbose_name = "Users" but this gives keeps showing this error return getattr(import_module(package), attr) AttributeError: module 'myapp.users.serializers' has no attribute 'CustomRegisterSerializer' -
Django REST Framework File Upload with React
I'm trying to use FileUploadParser from rest_framework.parsers to send a raw CSV directly from a client request, but I'm running into some trouble. On the client side, my File object looks like (the contents of the file itself are 'foo,bar'): File(7) {preview: "blob:http://localhost:5011/c576258c-cdcb-4cfa-88dd- f1c52fcfaffe", name: "testcsv.csv", lastModified: 1512578725000, lastModifiedDate: Wed Dec 06 2017 11:45:25 GMT-0500 (EST), webkitRelativePath: "", …} lastModified: 1512578725000 lastModifiedDate: Wed Dec 06 2017 11:45:25 GMT-0500 (EST) {} name: "testcsv.csv" preview: "blob:http://localhost:5011/c576258c-cdcb-4cfa-88dd- f1c52fcfaffe" size: 7 type: "text/csv" webkitRelativePath: ""} and in React i'm using the request: req.post(`upload/${file.name}`,file, (err, res) => { console.log(req) if (!err) { dispatch(createProjectFormHeaders(headers)); browserHistory.push(`/project/${data.id}/create-form- from-upload`); } }); When it hits Django however, the contents of the file are: request.data['file'].read() (Pdb) b'{"preview":"blob:http://localhost:5011/5cd55446-b6e2-4991-b568- 326485b1bbd8"}' and not 'foo,bar'. Is there a way to do this just using the FileUploadParser? Am I passing the file object incorrectly from the client? I would prefer to use this Parser instead of refactoring to use multipart/form-data. Thanks for any guidance. -
Building a survey with questions having dynamic choices
I am currently building a survey which consists of questions with choices. The various choices for a question can be entered through the admin page. These choices are then required to be displayed as a drop down for a particular question in a django form. I believe the Choicefield is necessary but am unsure how to implement it as there is documentation only on static choices. Thanks in advance. -
Python: how to sort a list of strings by substring?
I have some list of strings, for example: ["foo bar SOME baz TEXT bob", "SOME foo bar baz bob TEXT", "SOME foo TEXT", "foo bar SOME TEXT baz", "SOME TEXT"] I want it to be sorted by exactness to SOME TEXT substring (upper case doesn't matter). Something like this order: ["SOME TEXT", "foo bar SOME TEXT baz", "SOME foo TEXT", "foo bar SOME baz TEXT bob", "SOME foo bar baz bob TEXT"] The idea is - the best score gets the string with the best match to substring words position. And for bigger amount of "sloppy" words between substring's words - the lower ordering it gets. I have found some libraries like fuzzyset, or Levenshtein distance but I'm not sure this is what I need. I know the exact substring by what I want to sort and those libs search the similar words, as I understood. Actually I need to do this sort after some database query (Postgresql) in my Django project. I have already tried full-text search with its ORM, but didn't get this relevant sort order (it doesn't count the distance between substring words). Next I have tried Haystack+Whoosh, but also at this moment didn't find info how … -
Ajax not posting Select Option
I'm trying to get the value of the option in my template below called exampleid. I've followed several examples I found online, but nothing seems to work. My template below has the ajax and jquery to get the value but when I try to print it returns None. I've exhausted my resources and my professor doesn't seem to know, he's "looking into it". <form action = "{% url 'example' %}" form method = "POST"> <script> $(document).ready(function () { $('#exampleid').on('change', function () { var exampleid= $(this).val(); $.ajax({ url: "{% url 'example' %}", data: exampleid, type: POST, success: function (result) { alert(result); }, }); }); }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <select title ="accesslevelid" class="form-control" id="exampleid" onchange="exampleid"> <option value="1"> Option1</option> <option value="2"> Option2</option> <option value="3"> Option3</option> </select> </form> my view attempting to retrieve the value of the post. exampleidpost = request.POST['exampleid', False] print (exampleidpost) My desired result is for the POST to return a 1,2, or 3. -
Django UUIDField in admin search_fields
In a model I have a UUIDField like this: uuid = models.UUIDField(_('UUID'), primary_key=True, default=uuid.uuid4, editable=False) in corresponding adminisration I would to search by uuid value. So I have: class MyAdmin(admin.ModelAdmin): search_fields = ('uuid',) but in this way it does not produce any results. Have I to set somethink? I use Django 1.11 -
php error with sending email?
I use VPS+NGINX+DJANGO+GUNICORN My pip freeze: Django==1.11.7 django-pagedown==0.1.3 gunicorn==19.7.1 Markdown==2.6.9 I active my venv and run gunicorn. (venv) name@ubuntu:~/mysite$ ls accounts api_v0 boards manage.py mysite posts static templates (venv) name@ubuntu:~/mysite$ gunicorn --bind 0.0.0.0:8000 mysite.wsgi And get such mistake: Traceback (most recent call last): self.callable = self.load() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.6/dist-packages/gunicorn/util.py", line 352, in import_app __import__(module) File "/home/name/mysite/mysite/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'pagedown' What's the problem? -
Third party authentication using Django and Phonegap
In my mobile app, i need to provide signup or sign using Facebook, Twitter, and Google.I checked third-party authentication using Django but I can't be used Django template in my mobile application.Can someone please suggest how to implement this.I am quite new to both Django and PhoneGap technology -
How to run Celery Periodic task at every end of the month
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file. Now, I am using @periodic_task to call the function. But I need my task will run only on the last date of the month whether it is 31st, 30th, 29th or 28th depends on the month. I am getting the last date of month using this function: def get_last_date(): today = timezone.now() year = today.year month = today.month last_date = calendar.monthrange(year, month)[1] return str(last_date) My code for task looks like this: @periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True) def invoice_simulation(): generate_invoice() But this is not running! -
Same test for different states of the same object without persisting changes
I am trying to run the same exact test on a single obj which is a models.Model instance and has some relations with other models. I do not want to persist changes in that instance, so effectively I want the same effect of the tearDown method which rollbacks transactions. To illustrate this: class MyTestCase(django.test.TestCase): def test(): # main test that calls the same test using all # different states of `obj` that need to be tested # different values of data that update the state of `obj` # with state I simply mean the values of `obj`'s attributes and relationships data = [state1, state2, state3] for state in data: obj = Obj.objects.get(pk=self.pk) # gets that SINGLE object from the test db # applies the state data to `obj` to change its state obj.update(state) # performs the actual test on `obj` with this particular state self._test_obj(obj) def _test_obj(self, obj): self.assertEqual(len(obj.vals), 10) self.assertLess(obj.threshold, 99) # more assert statements... This design has two problems: The changes on obj persist on the test database, so on the next iteration the data would be tainted. I would want to rollback those changes and get a fresh instance of obj as if the test method was … -
Django model method to count method flag of foreignkeys
I have two models Assessment and Answer with a OnetoMany relationship. models.py class Assessment(models.Model): name = models.CharField(max_length=255, blank=False) def __str__(self): return "{}".format(self.name) def _all_answers_completed(self: #some how get all related answers #then see if "completed" = true #if all = true then return true #if any = false then return false completed = property(_all_answers_completed) class Answer(models.Model): assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.CASCADE) score_risk = models.IntegerField(default=0) score_impact = models.IntegerField(default=0) score_occurrance = models.IntegerField(default=0) def __str__(self): return "Answer to Question:{} for Assessment {}".format(self.question, self.assessment) def _is_answered(self): if self.score_risk > 0 and self.score_impact >0 and self.score_occurrance > 0: return True else: return False completed = property(_is_answered) I want to set the assessment method completed based on the related answers property answer.completed I just don't know how to do this or do I have to do this in a view via looping through a queryset. -
django creating user fixtures get CommandError: Unable to serialize Nonetype
I'm trying to create some fixtures for a test in django and trying to dump a user from the db which has a few users in it. However when I try to use dumpdata admin command I get an error: CommandError: Unable to serialize database: 'NoneType' object has no attribute '_meta' Presumably one of the users has None in one of it's fields (?) which may be causing the issue? However the error doesn't show what user or field. Is there a simpler way to generate some user fixtures? I'm using a custom user model (and also django allauth): class User(AbstractUser): MR = 'Mr' MRS = 'Mrs' MISS = 'Miss' MS = 'Ms' DR = 'Dr' SIR = 'Sir' PROF = 'Prof' REV = 'Rev' TITLE_CHOICES = ( (MR, 'Mr'), (MRS, 'Mrs'), (MISS, 'Miss'), (DR, 'Dr'), (SIR, 'Sir'), (PROF, 'Prof'), (REV, 'Rev'), ) title = models.CharField(max_length=5, null=True, choices=TITLE_CHOICES) date_of_birth = models.DateField(null=True) primary_phone = PhoneNumberField(null=True) mobile_phone = PhoneNumberField(null=True) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) -
Django CMS - How to make CKEditor automatically inherit HTML content inside the Placeholder tag?
I'm using CKEditor 4.7.3. I would like to be able to inherit the HTML content that is placed within the Placeholder tag automatically into CKEditor. My HTML code looks like this: <p class="info" data-aos="fade-down"> {% placeholder "test" or %} <i class="fa fa-circle-o" aria-hidden="true"></i> <span class="text-uppercase">Test:</span> Vestibulum tortor quam, feugiat vitae.{% endplaceholder %}</p> Currently Django CMS creates a 'Test' placeholder instance in Structure mode and when I add a 'Text' plugin to it I have to paste all HTML content manually to make it look like original site. Is there a way to make CKEditor automatically inherit the HTML content?