Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In a InlineFormset how do I change the method that display the errors?
In a InlineFormset how do I change the method that display the errors ? {{ form.documents.management_form }} {% for error in form.documents.errors %} {{ forloop.counter }} {{ error.document}} {% endfor %} By default they are unordered lists, but I want to change them, to integrate better with my UI. -
Replacing unicode characters with ascii characters in Python/Django
I'm using Python 2.7 here (which is very relevant). Let's say I have a string containing an "em" dash, "—". This isn't encoded in ASCII. Therefore, when my Django app processes it, it complains. A lot. I want to to replace some such characters with unicode equivalents for string tokenization and use with a spell-checking API (PyEnchant, which considers non-ASCII apostrophes to be misspellings), for example by using the shorter "-" dash instead of an em dash. Here's what I'm doing: s = unicode(s).replace(u'\u2014', '-').replace(u'\u2018', "'").replace(u'\u2019', "'").replace(u'\u201c', '"').replace(u'\u201d', '"') Unfortunately, this isn't actually replacing any of the unicode characters, and I'm not sure why. I don't really have time to upgrade to Python 3 right now, importing unicode_literals from future at the top of the page or setting the encoding there does not let me place actual unicode literals in the code, as it should, and I have tried endless tricks with encode() and decode(). Can anyone give me a straightforward, failsafe way to do this in Python 2.7? -
Accessing the same instance of a class django, python, heroku
I've been working on a website which allows users to play a game against a "Machine" player and I decided to do this using django 1.12 and python 3.6 in an attempt to develop skills in this area. The game & ML algorithms run on the backend in python and during testing/dev this all worked fine. When pushing this to heroku it became apparent that the instance from the game and other classes were being instantiated correctly but then as the page refreshes, in order to get the machine player's choice from the server, the request would go to another server which didn't have the instantiated objects. I tried using the default cache to allow the player to access the same instance but I believe it might be too large. After some reading it sounds like memcached is the way forward, but I wondered whether anyone might have any suggestions or know if there's a simpler solution? -
django admin interface show 403 errors for custom model
I have a django & drf application behing an apache as proxy. I can log in in admin interface and see core Model (like Users, Groups, Task Results and Token) and navigate through it, read the model documentation. On the other hand, my custom models are shown on the admin interface homepage but i can't navigate on it, read the doc. I receive a 403 error. The url called : https://server/admin/api/itemtype/ The page body returned : Forbidden You don't have permission to access /admin/api/itemtype/ on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. Did someone have any clue on this? -
Django Forms/Crispy forms errors not displaying
Im using crispy forms but I believe I dont need crispy to show errors? However, the current code below is not displaying any errors. I have an inkling there must be some as when I hit create I am returned back to the add form page with the data I typed filled in (as if there was an error) the page however displays nothing and the site is not created views.py @login_required @user_passes_test(lambda u: u.has_perm('sites.add_site')) def add_site(request): import ipaddress, re from sites.forms import AddSiteForm from config.models import SiteSubnets, SubnetTypes if request.method == 'GET': form = AddSiteForm() else: # A POST request: Handle Form Upload form = AddSiteForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): location = form.cleaned_data['location'] site_type = form.cleaned_data['site_type'] bgp_as = form.cleaned_data['bgp_as'] create_subnet = form.cleaned_data['create_subnet'] # create location new_site_data = SiteData.objects.create( location=location, site_type_id=site_type, bgp_as=bgp_as, ) # is site a remote site if create_subnet == True: generate_subnets(new_site_data.pk, create_subnet) return redirect('sites:site_overview', new_site_data.pk) return render(request, 'sites/add_site.html', { 'add_site_form': form, }) template.html {% block content %} {{ add_site_form.errors }} {% if add_site_form.errors %} {% for field in add_site_form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% … -
Error trying to access app locally - Heroku and python3
long time lurker first time poster - up til now i've been able to solve most of my problems using google-fu; however i really can't fine a fix for this one. I'm trying to follow the instructions on "Getting started on Heroku with Python", and I've gotten stuck at trying to install "collectstatic". When I try to run the command python3 manage.py collectstatic, I get this page of errors: `Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/markdenieffe/python-getting- started/gettingstarted/settings.py", line 14, in <module> import django_heroku ModuleNotFoundError: No module named 'django_heroku'` This is the first time i've actually used python … -
Django template tags beginner
How can I do this Example.html {% for number in numbers %} {{ number }} ##### 1 {{ Form1 }} ##### first loop {{ number }} ##### 2 {{ Form2 }} ##### second loop {% endfor %} Form1, Form2... have been passed though views -
Celery Beat - AttributeError: 'Settings' object has no attribute 'beat_schedule_filename'
I am using celery beat with my Django project and everything is deployed with Docker containers. Celery itself works fine, but celery beat returns the following error: AttributeError: 'Settings' object has no attribute 'beat_schedule_filename' My celery.py file is: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'user_api.settings') app = Celery('user_api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Inside the settings.py file I have set: CELERY_BROKER_URL = 'redis://redis' CELERY_BEAT_SCHEDULE = { some tasks here} I am running celery beat with: celery -A user_api beat as root. Tried to set in my settings beat_schedule_filename or CELERY_BEAT_SCHEDULE_FILENAME as "celerybeat-schedule" (even though it should have this value by default) but it did not fix the error. -
I want to change input format of a timepicker of moment.js from 2018-01-23T12:38:07.439Z to 12:38:07
I am using angular js material for template and angular js for js. and since no timepicker in angular material js I am using a timepicker of moment.js I am using Django as a backend. I am puting data in the database through rest api the code of my angular template is here: <md-input-container flex-gt-sm class="md-block"> <label>Opening Time</label> <md-icon md-svg-src="/cityaplfreelisting/media/time.svg" class="mdicon"></md-icon> <input required mdc-datetime-picker date="false" time="true" type="text" short-time="true" show-todays-date click-outside-to-close="true" auto-ok="true" min-date="minDate" minute-steps="1" format="hh:mm a" ng-change="vm.saveChange()" ng-model="data.openingTime "> </md-input-container> Actually my database is taking the value of openingTime in hh:mm:ss formar through rest api thats why I want to change the input format of time its showing in the format of 2018-01-23T12:38:07.439Z which is not acceptable for my django model This is my django model from django.db import models from django.contrib.gis.db import models as gis_models from django.contrib.postgres.fields import ArrayField from django.conf import settings from django.db.models.signals import pre_save from django.utils.text import slugify from multiselectfield import MultiSelectField class Shop(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) # will change on_dlt method soon subCategory = models.ManyToManyField(SubCategory) filterTags = models.ManyToManyField(FilterTag, blank=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) slug = models.SlugField(unique=True, blank=True) shopName = models.CharField(max_length=250) tagline = models.CharField(blank=True, max_length=500) bannerImage = models.ImageField(upload_to=upload_location, default='shop/defaultimage/default.png', width_field='widthField', height_field='heightField') widthField = … -
sum with condition in django query
We want to wrtie this query in django please SELECT count(recommended='1') AS YES,count(recommended='0') AS NO FROM `rating` WHERE applied_users = 32500 we have no idea how to use in sum "= 1" -
django: login_redirect_url not working
I have written my own login and logout views. I am using LOGIN_REDIRECT_URL to set the redirect page. My login view is fairly simple, def todologin(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) login(request, user) url = reverse('pilot:home') return HttpResponseRedirect(url) else: form = LoginForm() return render(request, 'login.html',{'form':form}) @login_required def home(request): I am using @login_required on my homepage. This is the value of the LOGIN_REDIRECT_URL, LOGIN_REDIRECT_URL = '/login/' # tried this one too, LOGIN_REDIRECT_URL = 'pilot:login' My app's urls.py, from django.conf.urls import url from . import views urlpatterns = [ url(r'^signup/', views.signup), url(r'^home/', views.home, name='home'), url(r'^login/', views.todologin, name='login'), url(r'^logout/', views.todologout, name='logout'), ] Still, it always redirects to /accounts/login/?next=/home/ Why is this happening? -
Python - Web scraping using beautifulSoup (Import into csv)
The code already can scrape more than 1 url, problem is that i want to import it into a csv file, i have try to do it but it will stop running at some point. what is the problem on this code, can someone help me. from bs4 import import BeautifulSoup import requests import cs url_list= ['pantai-klebang/4c7c12d22d3ba14318e595d0','porta-de-santiago-a-famosa-fortress/4d26d123ebacb1f77692e14f'] def scrape(url_to_scrape) i = 1 while True: r = requests.get('https://foursquare.com/v/{0}?tipsPage={1}&tipsSort=recent'.format(url,i)) soup = BeautifulSoup(r.content, "html.parser") reviews = soup.find_all("li", {"class": "tip"}) titles = soup.findAll("div", {"class": "primaryInfo"}) for title in titles: placeTitle = title.find("h1", {"class": "venueName"}).text f = open('{}.csv'.format(placeTitle), 'w') headers = "review\n" f.write(headers) writer = csv.writer(f) if len(reviews) != 0: for item in reviews: review = item.find("div", {"class": "tipText"}).text print(review.encode('ascii','ignore')) f.write(review.encode('ascii','ignore') + "\n") i += 1 else: break f.close() for url in url_list: scrape(url) -
About django URLs
Help! When I want to make new URL in django url.py and views.py like this urls.py and this views.py the server doesn't run in cmd like this Can you know why? -
python setup.py egg_info error mysqlclient
I just started learning Python using Django and I just seemed to be stuck at the same place for 3 days, every time I try to run the following command in my terminal using Pycharm (Yep, I am using a Mac) I get the below error: Command: pip install mysqlclient Error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-c7mudszc/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-c7mudszc/mysqlclient/setup_posix.py", line 44, in get_config (venv) Mervins-MacBook-Pro:untitled mervinkobola$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-w_jamo3b/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-w_jamo3b/mysqlclient/setup_posix.py", line 44, in get_config (venv) Mervins-MacBook-Pro:untitled mervinkobola$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup_posix.py", … -
GeoDjango - Leaflet show popup of a ForeignKey
I am trying to show the User's name on a popup using Leaflet. Right now, I am only able to return the foreignkey id/pk as a number, but I would want to show the user's actual name on the popup. (the name field in the model is shown correctly in the popup) Here is a simple model class Reserve(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() user = models.ForeignKey(User) name = models.CharField(max_length = 240) views def reserve_datasets(request): reserve= serialize('geojson', Reserve.objects.all()) return HttpResponse(reserve, content_type='json') html <script type="text/javascript"> function our_layers(map,options){ var all_reserve_datasets = new L.GeoJSON.AJAX("{% url 'reserve_datasets'%}",{ onEachFeature: function(feature,layer){ layer.bindPopup('<h4> Name: '+feature.properties.name+'</h4><p>User: '+feature.properties.user); }, }); all_applied_reserve.addTo(map); } </script> {% leaflet_map "gis" callback="window.our_layers" %} -
Wagtail - Add images on homescreen
Basically, I have want to be able to add new images from the admin panel to my lists section of my homepage. Here, basically: <div class="lists"> <div> <!-- List Nunti --> <div class="title"> <hr /> <h3>Nunti</h3> <hr /> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/203689226?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </div> </div> My homepage.models looks like this : class GalleryPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), InlinePanel('gallery_images', label="Gallery images"), ] class GalleryImage(Orderable): page = ParentalKey(GalleryPage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] -
ForeignKey to autogenerated (or equivalent) m2m Model in Django
I have two Django models A and B with a many-to-many relationship, and I need a third model C to have a ForeignKey that points to the intermediary model. Now, simply writing my own model and using through is by itself not a solution to my problem - I also have admin inlines for A that include a field for this m2m relationship - this breaks if I specify a custom intermediary model. I already tried doing class C(models.Model): ... b_c = models.ForeignKey(A.bs.through, ...) But that gives me (fields.E300) Field defines a relation with model 'A_b', which is either not installed, or is abstract. when I try to run makemigrations. Now, I understand the reasoning behind all this - intermediary models are created dynamically, so migrations don't manage them because that would cause a redundancy. Explicit intermediary models can't in general just be added/removed, because there may be additional data associated with them. This means that presenting them (for example) as a Select2 widget is, in general, not appropriate. In my case, however, I really only need that ForeignKey relation, and am OK if deleting data will lead to errors (I intend to use on_delete=PROTECT). Also, I can see how … -
How do I configure nginx to forward the request to some gateway servr which sends the response to client
I would like to process the request in django and add custom header to the request and let the nginx to forward the request to some gateway server resides on another machine. I attempted few trails, but doesn't seem it is working. Came across the proxy_pass which does pretty much same stuff, but sends the request to a specified proxied server, fetches the response, and sends it back to the client. I don't wish to get back the response to my nginx server and let the gateway server send the response directly to the client. I would like to get the request from nginx server and do pretty authentication, and add custom header to the request and forward to the gateway server which performs the logic and sends the response back to client directly. Here is the code: Django view response = Response() # response['User-Information'] = user.username response['X-Accel-Redirect']='/route/' return response Nginx conf. upstream gateway { server 192.168.1.45:3000; } location /route { proxy_pass http://gateway/postdata; proxy_method POST; } -
Does ViewSets generate view_names in Django Rest Framework?
I want to use HyperlinkedIdentityField in my serializer, that's why I need view name. How can I get the view name if I need model_name-list for example? -
Is there a regex statement to remove all print() statements from my Python/Django project?
I'm preparing to go into production so want to remove all my print() statements before pushing my development code onto my server. Wondering if there is a clean way to do this. -
Change BaseInlineformset validate_min, because is not correct/complete
Having an inlineformset: ProducFormSet = inlineformset_factory(parent_model=Product, model=ProductDoc, form=ProductDocForm, min_num=1, validate_min=True, extra=2, max_num=3, can_delete=True) The validation for validate_min=True is not correct, or not complete.It validates only if there are values in the first form. If the user add info in any of the extra forms, but not in the first form the validate_min is triggered, even if 2 forms are having information. I want/need to overwrite the validation min in the BaseInlineForm, to check all forms. -
How to create many to many relationship between models in Django Rest Framework
I have the following models and serializers: Models: class Site(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) class SiteCategory(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) Serializers: class SiteSerializer(serializers.HyperlinkedModelSerializer): class Meta : model = Site fields = ('id', 'name', 'created', 'categories') class SiteCategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SiteCategory fields = ('id', 'name', 'created', 'sites') I want to setup a many-to-many relationship between the sites and categories so for e.g.: Site1 categories: Category1, Category2. Site2 categories: Category2, Category3. Category1 sites: Site1. Category2 sites: Site1, Site2. Category3 sites: Site2. I'm kinda clueless on how should I set up my models and serializers to achive the output described about. -
How to create a new record from django query set
I have heard of a django orm hack somewhere. It goes like this dp = SomeModel.objects.filter(type="customer").last() dp.id = dp.id + 1 #changing id to a new one dp.save() The last step supposedly creates a new record provided the value of id being used doesn't exist. In case the incremented id exists, then the save method acts like the update method. example :: dp.version += 1 #updating some random field dp.save() # will change the newer version of dp.id I would like to ask veterans in django two questions for our benefit, Is there a sure shot way of creating a new record from an old record with the latest auto_increment_pk instead of pk + 1 method Is the above method any faster or better. One advantage I see is if I have a model with 10 fields and I want to create a new record from an old one with only 1 or 2 changes from the older one, this method saves 8 lines of code. Thank You -
Deleting objects that are not referenced by other objects
I have a need to cleanup my database, hence looking for an efficient way to DELETE all objects that are not referenced by other objects via the ForeignKey. Currently, I am doing the following: from django.db import transaction from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS from django.db.models.deletion import Collector from mygeo.models import Location locations = Location.objects.filter(office__slug='bb-co') with transaction.atomic(): for location in locations.iterator(): collector = NestedObjects(using=DEFAULT_DB_ALIAS) # database name collector.collect([location]) # list of related objects that will be deleted objects_to_delete = collector.nested() if len(objects_to_delete) == 1: location.delete() The above works well but takes a longer time to process, since I have over 100000 records to query. Is there a better way than the above to achieve this? -
How to filter the query_set by multi-params?
How to filter the query_set by multi-params? class UserListAPIView(ListAPIView): """ return the user list """ pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] def get_serializer_class(self): return UserListSerializer def get_queryset(self): username = self.request.query_params.get("username") real_name = self.request.query_params.get("real_name") phone = self.request.query_params.get("phone") company_name = self.request.query_params.get("company_name") return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username, real_name=real_name, phone=phone, company_name=company_name ) # if `username, real_name, phone, company_name` all are None, there gets `[]` The serializer: class UserListSerializer(ModelSerializer): """ user list serializer """ username = serializers.CharField(allow_null=True, allow_blank=True) real_name = serializers.CharField(allow_null=True, allow_blank=True) phone = serializers.CharField(allow_null=True, allow_blank=True) company_name = serializers.CharField(allow_null=True, allow_blank=True) You see, my username , real_name, phone, company_name all are allow_null. I want to query all the user that meet the conditions. But gets [], when I do not pass the username, real_name, phone, company_name. I want to if the username is None, it do not filter the username, if real_name is None, it do not filter the real_name. (I means it do not filter out it) I have a idea, but it is fit for less fields, if there is only one username field: def get_queryset(self): username = self.request.query_params.get("username") if username == None or username == '': return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False) else: return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username) But there …