Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template filter queryset
I'm new in django. I has a django application where stores products categorized by 'X' and 'Y'. views.py ... class CartListView(ListView): template_name = 'checkout/list.html' context_object_name = 'product_list' def get_queryset(self): return Product.objects.filter(category__slug='X') | Product.objects.filter(category__slug='Y') def get_context_data(self, **kwargs): context = super(CartListView, self).get_context_data(**kwargs) context['minicurso'] = get_object_or_404(Category, slug='X') context['pacotes'] = get_object_or_404(Category, slug='Y') return context ... In my views.py I filter this products by your categories slug. The problem is, I'm trying to render the products in category 'X' on top the page and the products in category 'Y' down with a text between them. How I can do this? list.html {% for category in product_list %} {{ category.name }} {% endfor %} <p> Any text </p> {% for category in product_list %} {{ category.name }} {% endfor %} -
Running python script automatically in django
Is there a way I can run a py script on Django automatically after I have uploaded the py file and print the results out on the website? -
how do i setup django in wamp?
I want to test my django app in my WAMP server. The idea is that i want to create a web app for aaa.com and aaa.co.uk, if the user enter the domain aaa.co.uk, my django app will serve the UK version, if the user go to aaa.com, the same django app will serve the US version (different frontend). Basically i will be detecting the host of the user and serve the correct templates. How do i setup my WAMP so i can test this? right now i am using pyCharm default server which is 127.0.0.1:8000 -
Getting data to Heroku psql with heroku app
I've got a Django app up and running on Heroku and have configured it for postgresql. I have ~40000 pieces of data on the local DB. When I push this to Heroku, I don't see any of the data in the Django DB admin atleast. Am I looking in the wrong place or doing something wrong? Here is some settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': os.path.join(BASE_DIR, 'db.postgresql'), 'NAME': 'csci2133', 'USER': 'kenny', 'PASSWORD': '...', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 500, } } #Configure heroku for djangos database db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I've also tried hosting a file I exported from postgres as a text, SQL file seperated with ;. But this didnt do anything.. What am I doing wrong? -
Django user has_perm returning false even though group has permission
I'm running into a problem where I've created a Group with certain permissions, and successfully added a user to that group, but when I check user.has_perm with that permission, I'm getting False. I've even tried things like saving the user and re-fetching them from the database to avoid caching issues, but it makes no difference. The terminal output below should give an idea of what's happening # Get a group from the database and check its permissions > special_group = Group.objects.get(name="special_group") > a_perm = special_group.permissions.all()[0] > a_perm.codename 'some.permission' # Get a user from that group and check if they have those permissions > a_user = special_group.user_set.all()[0] > a_user.has_perm(a_perm.codename) False > a_perm.codename in a_user.get_group_permissions() False # Curiously, get_group_permission sort of returns what we need > a_user.get_group_permissions() {'ContentType object.some.permission'} # If we essentially coax the group_permissions into a list and pull an item out of there, has_perm returns true, but this string is different to a_perm.codename > a_user.has_perm(list(a_user.get_group_permissions())[0]) True Does anyone know why has_perm isn't behaving as I'm expecting? We are using Django 1.10.3. -
403 error code when using axios.post to Django endpoint in React app
I am getting a 403 when I try to make a simple post request to a django view from within my react app. Here is my code: views.py @csrf_protect def test_view(): if (request.method == 'POST'): return HttpResponse(request.body) Login.js (React component) import Cookies from 'js-cookie'; //React constructor { test_view() { const csrftoken = Cookies.get('csrftoken'); const config = { headers: {'HTTP_X_CSRFTOKEN': csrftoken}, } axios.post('/prototype/hello/', {firstName: 'Fred'}, config) .then(res => {console.log("Test res: " + res.data)}); } //} urls.py url(r'^hello', views.test_view, name='test-view'), Is it possible that the 'js-cookie' library isn't working? I don't have {% csrf_token %} anywhere because I'm not using a django template other than index.html. Instead, I have the @csrf_protect decorator. I think that is what I'm supposed to do based on the docs. -
Trying to override Django User model username validation
I am trying to override the django default User model username field to allow hashtags in usernames. I know the model itself will let me do this but the standard form registration doesn't seem to allow it. I'm using django-allauth as well. How do I replace the regex in the default User model form to allow a hashtag in the username? -
Filter objects from another in django admin
In the django admin when the user adds an animal, I need to only see the "troops" that belong to the "farm" when selecting the "farm" field in the "troop" field. That is, respect the foreign key. class Troop(models.Model): name = models.CharField(max_length=255) farm = models.ForeignKey(Farm) class Farm(models.Model): name = models.CharField(max_length=255) class Animals(models.Model): rp = models.CharField(max_length=50) name = models.CharField(max_length=50) farm = models.ForeignKey(Farm) troop = models.ForeignKey(Troop) Thanks -
unique_together does not work in Django shell
I have below model: class Property(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) app = models.ForeignKey(App, on_delete=models.CASCADE) name = models.CharField(max_length=120) value = models.CharField(max_length=350, blank=True) description = models.TextField(blank=True) pub_date = models.DateTimeField('date_published', default=timezone.now) class Meta: verbose_name_plural = "properties" unique_together = (('value', 'name'),) def __str__(self): return self.name When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect. But in manage.py shell: >>>from myapp.models import App, Property, Job >>>from django.shortcuts import get_object_or_404 >>>app = get_object_or_404(App, app_name='BLABLA') >>>job = get_object_or_404(Job, job_name='BLABLA2') >>> Property.objects.create(job=job, app=app, name='1', value='1') <Property: 1> >>> Property.objects.create(job=job, app=app, name='1', value='1') <Property: 1> In this case I do not get any exceptions and objects are added in database. I tried makemigrations, migrate and migrate --run-syncdb. Django 1.9.12, sqlite3 -
Adapt translation method from django to my function
I am working on a django project. I have created a function that will display the current date in french or english. We have to install sudo locale-gen fr_FR.utf8 and then from datetime import datetime import locale def set_locale(locale_): locale.setlocale(category=locale.LC_ALL, locale=locale_) def date_customerprofile(language): now_ = datetime.today() if language == 'English': set_locale('en_US.utf8') date_ = now_.strftime("%A %B %d %Y") else: set_locale('fr_FR.utf8') date_ = now_.strftime("%A %B %d %Y") I know it works well, but I would like to use the django translation method. There are good informations here : https://docs.djangoproject.com/fr/1.10/topics/i18n/translation/ and in particular here : https://www.technomancy.org/python/django-i18n-manually-turn-on-a-language/. Could anyone be able to adapt the last website method to my function? I tried something but that doesn't work : from django.utils import translation def date_customerprofile(language): now_ = datetime.today() old_lang = 'en' if language == 'English': import ipdb; ipdb.set_trace() translation.activate('en') date_ = now_.strftime("%A, %B %d %Y") else : translation.activate('fr') date_ = now_.strftime("%A, %d %B %Y") translation.activate(old_lang) return date_ If I execute date_customerprofile('English'), it returns me something in French, i.e., 'mercredi, mars 29 2017' Thanks in advance! -
Render the same template with different text?
I have about 4-5 templates for my Django project. I want to use each template across about 10 pages(with 10 different sets of content/text) each. I've been using contexts to fill out the relevant content on each page when it is rendered. However, I'm not sure about any potential performance loss because the content is quite large. Is there a neat and efficient way to render one template with content relevant to a link clicked on a previous page. what I'm currently doing: index.html <div class='well well-sm well-md well-lg'> <h1> {{variable1}} </h1> </div> views.py def page1(request): variable1 = 'Long text for each variable. Many variables on each page so lots of long text overall. ' return render(request, 'index/base.html', {'variable': variable1}) def page2(request): variable1 = 'More long text. ' return render(request, 'index/base.html', {'variable': variable1}) Basically I want to know if there is a way of doing the above without having to use contexts. Or will I have to create a template for each page? -
How do I use django-treebeard to build a sitemap?
I have setup a django-treebeard model that has child nodes and what not. How do I now display this in my template? This is what I have so far. My Models: class SiteMapEntry(MP_Node): name = models.CharField(max_length=100, null=False, blank=False) url = models.CharField(max_length=1000, null=False, blank=False) node_order_by = ['name'] class Meta: verbose_name = "Sitemap Entry" verbose_name_plural = "Sitemap Entries" def __unicode__(self): return ('%s - %s' % (self.name, self.url)) My Views: from django.views.generic import ListView class SiteMap(ListView): model = SiteMapEntry template_name = 'sitemaps.html' My Template: {% block content %} <h1>Sitemap</h1> <br /><br /> {% for url in object_list %} <p>{{ url.name }}</p> <p>{{ url.url }}</p> {% endfor %} {% endblock content %} What this is doing right now, obviously is just listing the nodes and its children without any indenting. How do I list it like a tree in my template? -
newbie: idled python def
I'm feeling a rabbit posting this question, but I don't continue because this: What's is wrong with this stretch of my code: When I put something after the "if" I receive: IndentationError: unindent does not match any outer indentation level For example, if I put "cont =3" after the "if" and before "post = form2.save(commit=False)" I receive: File "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py", line 59 post = form2.save(commit=False) ^ IndentationError: unindent does not match any outer indentation level If I put the same expression but before of "post = form2.save(commit=False)" I receive: File "/home/douglas/Documentos/Django/my-second-blog/site_/app/views.py", line 59 cont = 3 ^ TabError: inconsistent use of tabs and spaces in indentation the code: def evaluation(request): # form2 initialization list_evaluation = Evaluation.objects.all() form2 = EvalForm() cont = 0 if request.method == "POST": form2 = EvalForm(request.POST) if form2.is_valid() == True: post = form2.save(commit=False) post.save() return redirect('canditate_list') else: form2 = EvalForm() return render(request, 'app/evaluation.html', {'criterions': form2,}) -
IIS rewrites and handlers conflict
I'm trying to set up a Django/Angular application under IIS. When I set a similar application under nginx, I pass all URLs starting with /api (my backend) or /admin (the Django admin interface) to Django. I also set two locations: / and /static - both are aliases to the folder with all the static resources. I need to alias /static, too, because Django's admin application references resources at /static/admin/... I can't get IIS to work the same way. I'm using wfastcgi to interface with Django, and a rewrite rule to map /static back to /. This is the relevant portion of my Web.config: <rewrite> <rules> <rule name="Static Perfix" stopProcessing="true" > <match url="^static/(.+)" /> <action type="Rewrite" url="{R:1}" /> </rule> </rules> </rewrite> <handlers> <add name="Admin" path="/admin" verb="*" modules="FastCgiModule" scriptProcessor="..." resourceType="Unspecified" /> </handlers> This doesn't work. When I access /admin the handler catches it and forwards the request to Django, as it should. Django return an html page with resources located at /static/admin/base.css (for example). When the browser tries to load such a resource the rewrite rule catches it, rewrites it to /admin/base.css, and then the handler catches it and forwards it to Django, which doesn't know what /admin/base.css is and returns a … -
How do I serve an angular 2 app from django's development server?
I have a project where I am using Angular2 to consume a rest API that I built with Django-Rest-Framework. Currently I have to start up the django api using django development server e.g., 'python manage.py runserver' and then I have to start up the angular 2 server using either 'npm start' or through the cli, 'ng serve'. Is there any way I can setup my django project to serve the angular2 project? -
How to run python script as a web service with user provided image?
I have a Python(2.7) script which detects faces in an image which works fine. from PIL import Image import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg") # Find all the faces in the image face_locations = face_recognition.face_locations(image) # a = print("Found {} face(s) in this photograph.".format(len(face_locations))) for face_location in face_locations: # Print the location of each face in this image top, right, bottom, left = face_location print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) # You can access the actual face itself like this: face_image = image[top:bottom, left:right] pil_image = Image.fromarray(face_image) pil_image.show() Now, I want to make it as a http://localhost:8080/detect so that user can provide an image and clicking on Submit button will display the output. I think there are few ways to do this, either using Flask, Django or Web server. But not sure which is the simplest way to do this and how to go about it. How to take this code and convert into a webservice? What code changes are required? Any code sample will be of great help. -
Configure heroku root domain in 123 reg
I've managed to point my site "www.mysite.com" to "www.mysite.com.herokudns.com" with a CNAME in 123 reg, but am now struggling to get the root domain "mysite.com" to point to the DNS Target "mysite.com.herokudns.com" which was created when I added the domain to heroku. I've tried * and @ as the DNS Entry but neither have seemed to work. www worked for the CNAME that is working as mentioned. Does anyone know what to do, or the best practice for dealing with urls like this? -
Django - periodic tasks - django-crontab
I have simple model with init_date field and end_date field. I'd like to delete/modify object after an amount of time. I installed django-crontab module. Is it possible to run cron job automatically after deploying my application on server (without additional configuration like python manage.py crontab add)? Maybe there is siplier method to do this simple task? There will be above 100 objects. I need to check every object and compare init_date and end_date. Cron is new for me and I don't know how to use it properly. -
Django and django-pyodbc error NotImplementedError SQL Server v8 is not supported
I'm working with Django and PyODBC to connect to a SQL Server 2000 database and I'm gettinh this error: Exception Type: NotImplementedError Exception Value: SQL Server v8 is not supported. My traceback: Environment: Request Method: POST Request URL: http://localhost/sistemas/cadastro_paciente/ Django Version: 1.10.5 Python Version: 2.7.12 Installed Applications: ['admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cadastro', 'fenotipo', 'cuser'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'cuser.middleware.CuserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/var/www/sistemas/cadastro/views.py" in cadastro_paciente 1297. if pacienteDB and pacienteHGP: File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __nonzero__ 264. return type(self).__bool__(self) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __bool__ 260. self._fetch_all() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _fetch_all 1087. self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __iter__ 54. results = compiler.execute_sql() File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql 824. sql, params = self.as_sql() File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/compiler.py" in as_sql 82. supports_offset_clause = self.connection.sql_server_version >= 2012 File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in sql_server_version 390. with self.temporary_connection() as cursor: File "/usr/lib/python2.7/contextlib.py" in __enter__ 17. return self.gen.next() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" … -
Integrity error when trying to save twice the same object using save_formset
I am out of ideas and I need some help about a problem that I encounter when I try to save the same object. Let me explain. I have a model, let's call it Pizza. And Topping which has a foreign key to Pizza: I have implemented an Admin view PizzaAdmin and I have added a tabular inline of Topping so from PizzaAdmin, I can add several toppings. I have override the save_formset method where I call a helper to perform a third-party API call. From the API response, I need to save some data to my toppings. def save_formset(self, request, form, formset, change): super(PizzaAdmin, self).save_formset(request, form, formset, change) helper = ApiHelper(instance=form.instance) helper.sync() This helper makes a call to an API, parse the response and associate an ID for each toppings of Pizza. class ApiHelper(...): def sync(self): # parse response for topping in self.instance.toppings.all(): if ....: topping.some_id = ... topping.save() When I reach the topping.save(), I got this error: IntegrityError I do not want to create a new Topping but update its property some_id. After futher investigation, I realised that save_formset is called by save_related which is called by changeform_view which as the decorator @transaction.atomic Is there a way to … -
Can I add data to Herokus DB via command line?
I've got a Django app on Heroku, but I am stuck using sqlite3 in django because my computer is not letting me deal with mysql or postgres.. I know I can add data in via the admin page, so I am wondering if I can have a script send data to heroku? -
validate email when using modelForm
I have developed a customized form which asks for the type of user. When filling a form i need to validate the email part. For that i have overridden clean function but the validation is not working. The signup process is not even touched into validation part.I think its because i have used UserProfile model where there is no email field.If that is the case, how can i solve it? Here is my code Note: I am using django-allauth ACCOUNT_SIGNUP_FORM_CLASS = 'account_page.custom_form.SignupForm' class UserProfile(models.Model): DESIGNER = 'designer' DEVELOPER = 'developer' BOTH = 'both' CHOICE = ((DESIGNER, 'designer'), (DEVELOPER, 'developer'), (BOTH, 'both')) user = models.OneToOneField(User, related_name="profile") user_type = models.CharField(choices=CHOICE, max_length=50, blank=False, null=False, default=DESIGNER) def __str__(self): return self.user.username from user_account.models import UserProfile class SignupForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_type'] def clean(self): email = self.cleaned_data.get('email') if email and settings.INVITE_MODE: try: obj = Invitation.objects.get(email=email) if not obj.request_approved: self.add_error('email', 'Sorry you are not accepted yet') except Invitation.DoesNotExist: invitation = Invitation.objects.create(email=email) self.add_error('email', 'Sorry we have added you to our invite list') elif email is None: raise forms.ValidationError('Email field should not be empty') else: return email def signup(self, request, user): profile = UserProfile() profile.save(commit=False) # user.save() user.profile = profile profile.user = user profile.user_type = … -
Save nested object with serializer in django rest framework
I'm getting a Json response to save it in my database, I need to get the items in line_items object. My Serializer and View works fine if I remove the line_items attribute in the model, but when I try to get that object and save it in the database nothing happens. Maybe I'm missing something in my serializer? Json Structure: { "id": 123456, "email": "jon@doe.ca", "created_at": "2017-03-29T15:56:48-04:00", "line_items": [ { "id": 56789, "title": "Aviator sunglasses", "quantity": 1 }, { "id": 98765, "title": "Mid-century lounger", "quantity": 1 } ] } My model: class Line(models.Model): title = models.CharField(max_length=100) quantity = models.IntegerField() class Order(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField() total_price = models.DecimalField(max_digits=6,decimal_places=2) line_items = models.ForeignKey(Line) My Serializer: class OrderSerializer(ModelSerializer): class Meta: model = Order fields = '__all__' My View: @api_view(['POST']) def orders(request): if request.method == 'POST': json_str = json.dumps(request.data) resp = json.loads(json_str) serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) -
django complex query for interdependant tables
Django Models class Product(models.Model): product_name = models.CharField(max_length=50) category = models.CharField(max_length=50) desc = models.CharField(max_length=120) company_name = models.CharField(max_length=50, default=None) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): return self.product_name class ProductDetails(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) batch = models.CharField(max_length=50) quantity = models.IntegerField() cost = models.FloatField(null=True, blank=True, default=None) mfg = models.DateTimeField() exp = models.DateTimeField() timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): return self.batch class product_barcode(models.Model): batch = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) barcode = models.BigIntegerField() flag = models.IntegerField() timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) updated = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): return self.barcode i want to calculate number of barcodes generated by company_name i tried some some code like w=Product.objects.all().filter(company_name="comapnay name") print "w>>>",w pid = [] for Pdata in w: pid.append(Pdata.id) print "pid>>>",pid here i find ids of product name which belong to specific company but after that i want to find batch codes(at ProductDetails) belongs to product ids ,after that i need to count all barcode belongs to batch codes in simple words 1->company ['company name'] 2->products ['product1','product2','product3'] where company = 'company name' 3->Batch codes where products = ['product1','product2','product3'] product1 … -
Fine tuning Django queryset retrieval
In a Django app of mine, I need to display, for a list of users (called user_ids), their: username, avatar and score. The username is retrieved from the User model, whereas avatar and score are present in the UserProfile model (that has a one-to-one field point to the User model, called user). Currently my approach is to fetch the full objects (see below), even though I just need 3 attributes from the two models. What's the most efficient way for me to just retrieve just the required fields, nothing else? Now I know i can do: usernames = User.objects.filter(id__in=user_ids).values_list('username',flat=True) scores_and_avatars = UserProfile.objects.filter(user_id__in=user_ids).values_list('score','avatar') However, these give me separate querysets, so I can't iterate over them as a unified object_list and show each user's username, score and avatar in a Django template. So what would be the most efficient, light-weight way to retrieve and put this information together? Currently, I'm doing the following to retrieve these three fields: queryset = User.objects.select_related('userprofile').filter(id__in=user_ids)