Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
combining two django models into one form
I am trying to make a signup form for teachers and the subjects they teach. I created two different models for them. class Teacher(models.Model): ... class Subject(models.Model): ... I have a foreign key to connect the subject to teacher since some teachers can teach more that one subject. My problem is I am trying to create the django form of teacher and a subform of subject and a button to add another subject form if necessary. Can anyone point me in a direction to get this done preferable with django. -
Order by formula
I'm filtering for stores. And I need to sort the stores by rating but the rating is considered by a complex form, I can sort them by one field but how to count for each I do not know that is current version order by rate shops = shops.order_by('rate') But you need to put the formula instead of the field rate, how is this done? -
Filter list of objects by self.request.user in Django
I cannot get this to work: class MyView(generic.ListView): context_object_name = 'my-model-list' template_name = 'my_models.html' def get_queryset(self): return MyModel.objects.filter(user=self.request.user) I have also tried return MyModel.objects.filter(user=User.objects.filter(name=self.request.user)) It seems that self.request.user is returning a name. The error I get is Cannot query "a": Must be "User" instance. The user's name is "a". My model is class MyModel(models.Model): user = models.ForeignKey(User) Can anyone help me? Thank you in advance. -
getting a 401 when trying to log in my users
I'm doing testing and I'm not being authenticated. class BaseTestCase(TestCase): def setUp(self): self.user_ben = User.objects.get(username='Ben312') self.client = Client() self.client.login(email=self.user_ben.email, password=self.user_ben.password) Here I have the function I'm trying to test: def test_add_tag(self): url = reverse('post_add_tag') response = self.client.post(url, {"tag": "cats", "post_id": 11}) self.assertResponse200(response) I get an assert error: self.assertEqual(response.status_code, 200) AssertionError: 401 != 200 Where am I going wrong with this? I obviously tried to have my user logged in but nope, Django is acting up on me. -
Django - ValidationError "value must be an integer"
I was recycling some of my code from an old project (Django 1.7) to use it in a new one (Django 1.8), so I get this Error every time I want to Login It was working well in Django 1.7 For my models I'm using an AbstractBaseUser models.py class Student(AbstractBaseUser, models.Model): email = models.EmailField(max_length=50) user_id = models.CharField(max_length=8, null=False, editable=False, default=id_generator, primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) prom_code = models.CharField(max_length=8, null=False, default="") gender = (("M","Male"),("F","Female"),) gender = models.CharField(max_length=1, choices=gender, default="M", null=False) USERNAME_FIELD = 'email' @property def is_superuser(self): return False def has_perm(self, perm, obj=None): return False def has_module_perms(self, app_label): return False @property def is_staff(self): return False def save(self, **kwargs): if not self.user_id: self.user_id = id_generator() while Student.objects.filter(user_id = self.user_id).exists(): self.user_id = id_generator() super(Student, self).save() I made a custom Authentication auth_backend.py from registration_app.models import Student import md5 class ClientAuthBackend(object): def authenticate(self, username=None, password=None): try: user = Student.objects.get(email=username) password_ver = md5.new(password).hexdigest() if user.check_password(password_ver): return user else: print("Entre aqui") return None except Student.DoesNotExist: print("Entre aqui2") return None def get_user(self, user_id): try: user = Student.objects.get(user_id=user_id) if user is not None: return user except Student.DoesNotExist: return None views.py def user_login(request): args = {} form = LoginForm(request.POST) username = request.POST.get('email', '') password = request.POST.get('password', '') user = … -
How do I create a model instance from field_dict for models with m2m fields
I could use some help. I have django-reversion set up, it's tracking changes to one of my models that has a few many-to-many relationship with other models. The problem I'm running into is in my UpdateView. I'm trying to create a model instance for my ModelForm, but the many-to-many field data is ignoring reversion's field_dict data and is displaying what's currently in the actual db associated with that model. The "parent model" is called Allergy, which has a many-to-many relationship to Allergen. Here's my UpdateView's get_object method and a helper function to construct an instance of the Allergen model that represents reversion's version data: def get_object(self, queryset=None): allergy_id = self.kwargs['allergy_id'] allergy_inst = get_object_or_404(Allergy, pk=allergy_id) version_id = self.kwargs.get('version_id') if version_id: return create_allergy_from_version(allergy_inst, version_id) else: return allergy_inst def create_allergy_from_version(allergy_inst: Allergy, version_id: int) -> Allergy: versions = Version.objects.get_for_object(allergy_inst) version_with_id = versions.get(revision_id=version_id) allergy_inst = Allergy(**version_with_id.field_dict) allergen_versions = version_with_id.revision.version_set.filter( content_type=ContentType.objects.get_for_model(Allergen) ) # do something here to associate *reversion's* allergen data to allergy_inst, not sure what! return allergy_inst -
Python/Django - UNIQUE constraint failed
I could'nt solve my problem even if I looked other people who had this problem. Problem is UNIQUE constraint failed.How to create a id with foreign key guys ? , and how can I use the id. this is my code. class Receipt(models.Model): amount = models.DecimalField(max_digits=5, decimal_places=2, primary_key=True) vat = models.DecimalField(max_digits=5, decimal_places=2, primary_key=True) total_amount = models.IntegerField(default=0, primary_key=True) class ReceiptItem(models.Model): receipt_id = models.ForeignKey('Receipt', on_delete=models.CASCADE, unique=True ) product_id = models.ForeignKey('Product', on_delete=models.CASCADE, unique=True) amount = models.DecimalField(max_digits=5, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) vat_rate = models.DecimalField(max_digits=5, decimal_places=2) sub_total = models.IntegerField(default=0) name = models.CharField(max_length=200) class Product(models.Model): name = models.CharField(max_length=5, primary_key=True) vat_rate = models.DecimalField(max_digits=5, decimal_places=2, primary_key=True) amount =models.IntegerField(default=0, primary_key=True)` and the error is django.db.utils.IntegrityError: UNIQUE constraint failed: migros_product.amount -
Trying to access Django REST API in Angular2
I am working on a project where we use Angular2 and a Django backend that has a rest API. Right now we are simply just trying to get the django backend to send JSON objects to Angular2. For some reason when we make get requests, it comes back as blank. Right now we just have dummy test functions, but even those don't work. /_services/user.service.ts tempFunc() { return this.http.get('http://localhost:8000/chains/', this.jwt()).map((model: Response) => model.json()); } /temptemp-page.component.ts import { Router } from '@angular/router'; import { UserService } from '../_services/user.service'; export class Temp { name : string; description : string; slogan : string; founded_date : string; website : string; } @Component({ selector: 'app-temp-page', templateUrl: './temp-page.component.html', styleUrls: ['./temp-page.component.css'] }) export class TempPageComponent implements OnInit { model: Temp; constructor( private router: Router, private userService: UserService) { } ngOnInit() { this.model = { name: 'Wrong', description: 'Wrong', slogan: 'Wrong', founded_date: 'Wrong', website: 'Wrong', } this.userService.tempFunc().subscribe(model => this.model = model); console.log(this.model); } } The Wrong is there just to know that if we get nothing, it will print Wrong and we know the get request isn't succeeding. temp-page-componenent.html <div style="margin-left: 20px;"> name: {{ this.model.name }} <br/> description: {{ this.model.description }} <br/> slogan: {{ this.model.slogan }} <br/> founded_date: {{ … -
How to avoid repetition on templates in Django?
I have the following code that is repeated on several templates: {% for element in elements %} <div class="some-class"> <div class="another-class"> <div class="row"> <div class="col-xs-3"> <img class="img-responsive" alt="{{ entry.user }} avatar" style="border-radius: 50%; width: 100%;" src="{{ entry.avatar_url}}"> </div> <div class="col-xs-9" style="some-style"> {% if entry.data1 %}<small>{% trans entry.data1 %}</small><br>{% endif %} {% trans entry.data2 %} {% trans entry.data2 %} <br> <small style="some-style"> {% blocktrans with timestamp=entry.timestamp|naturaltime %} {{ timestamp }} {% endblocktrans %} </small> </div> </div> </div> </div> {% endfor %} I was wondering what is the best way to avoid repeating this piece of code, I am kind of newbie to Django, and I would really appreciate your help. -
How to get the id where it is updating the data of the same in the form.save ()
Necesito capturar el ID de la Orden Modelo, donde a través de la plantilla ingresé la cantidad que se actualizará y almacenará con el mismo ID In this views.py code I save with form.save but create a new record with a new id, I need to take the one that is entering the amount and save it this way. def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user if user.is_superuser: pedido = Pedido.objects.filter(especialidad=especialidad) form = PedidoEditForm(request.POST, instance=pedido) if form.is_valid(): pedido = form.save() pedido.estado = 'pendiente' pedido.fecha_pedido = datetime.now() pedido.save() return HttpResponseRedirect('/solicitar/home/') else: form = PedidoEditForm() return render(request, 'admindata.html', locals(),{'form':form}) html: <form id="myform" method="post"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>id pedido</td> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td>Ingresar</td> <td></td> </tr> </thead> <tfoot> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>stock</td> <td>Cantidad</td> <td>Fecha Pedido</td> <td>Estado</td> <td></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ped.id}}</td> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> <td>{{ ped.articulo.stock }}</td> <td>{{ ped.cantidad }}</td> <td>{{ ped.fecha_pedido }}</td> <td>{{ ped.estado }}</td> <td>{% csrf_token %} {{form.as_p}}</td> <td><input type="submit" form="myform" class= "btn btn-success" value="Guardar"></td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> </div> … -
Annotation with Count + Condition + distinct Django
Hi anyone know how to make annotation with Count + Condition + distinct Django? Big thx for help. In docs there is simple count example: q = Book.objects.annotate(Count('authors', distinct=True)) But if replace 'authors' with a model condition (Case, When) if don't count correctly. -
How to construct a valid GET link in a pandas table and then render to html in a django view
Here is the task I try to solve: Add a column to a given pandas table and add some links to it. Render the table to html an show the table in a django template Here is the code (Python 3.6 and Django 1.10.5): views.py def test(request): data = { 'Age': ['23', '35'], 'Name': ['Benny', 'Johny'], } table = pd.DataFrame(data) table.insert(loc=2, column='Link', value='') number1 = 1234 number2 = 5678 # This is not working link = f'<a href="/anotherview/?param1={number1}&param2={number2}">Click Me</a>' table.set_value(index=1, col='Link', value=link) htmltable = table.to_html(index=True, border=1, na_rep='', justify='left', escape=False) return render(request, 'test.html', {'table': htmltable}) Template: test.html <!DOCTYPE html> <html lang="de"> <head> </head> <body> {% autoescape off %} {{ table }} {% endautoescape %} <!-- This is working --> <a href="/anotherview/?param1=1234&param2=5678">Click Me</a> </body> </html> The problem is that the link doesn´t render properly. Here is a picture of the rendered HTML sourcecode: Rendered HTML It works when I put the link directly into the HTML. I´m pretty sure it has something to do with djangos or pandas autoescaping or some kind of masking some characters (the '&') the wrong way, but i can´t figure out how to do it correctly. Who has an advice? -
Can't find table in django
I have put my django app online and have problem with using database. I am using my database as deault. In settings there is standard setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'mydatabase.db'), } } This works really well on local, but after hosting his app online I get error: "no such table: mydatabase" When I run python manage.py shell and start with standard: from app.model import Databaseclass everything is ok but then when I type Databaseclass.objects.all() I get the same error. I did all migrate, makemigrations, syncdb etc. I THINK that the problem is in 'settings' in this line: 'NAME': os.path.join(BASE_DIR, 'mydatabase.db'), because directory for database can be different on local and online. I have used advice from this website: Where is the sqlite database file created by Django? and typed in shell os.path.abspath(settings.DATABASES['default']['NAME']) after that I received a path (different that on local) but I don;t know how to use this path in settings to finally get access to my database. Please advice. -
Django Admin and Stripe Testing
I have a simple model that gets a charge id from stripe and stores it with a customer (an already existing Django user). Everything runs fine I think. The charge goes through successfully and stripe recognizes it on their test payments. It also displays the errors correctly both in the form and from Stripe. I also have an admin section that lists the charge and customer. After I run a test charge that is successful nothing is added to the admin page. Does Django know this is just a test and not to add it to the admin? -
How to count and compare in Django
Currently have a database with 10 questions which posts a number from 1-4 i just want to add that number up to create a total then only show the closest match for that total number Models.py class Question(models.Model): name = models.CharField(max_length=10, primary_key=True) question1 = models.CharField(max_length=50, choices=Question1_CHOICES) question2 = models.CharField(max_length=50, choices=Question2_CHOICES) question3 = models.CharField(max_length=50, choices=Question3_CHOICES) question4 = models.CharField(max_length=50, choices=Question4_CHOICES) question5 = models.CharField(max_length=50, choices=Question5_CHOICES) question6 = models.CharField(max_length=50, choices=Question6_CHOICES) question7 = models.CharField(max_length=50, choices=Question7_CHOICES) question8 = models.CharField(max_length=50, choices=Question8_CHOICES) question9 = models.CharField(max_length=50, choices=Question9_CHOICES) question10 = models.CharField(max_length=50, choices=Question10_CHOICES) Views.py def comparison(request): return render(request, 'music/compare.html', dict(rows=Question.objects.all(), total=Question.objects.count())) I tried using total with count but I don't think its correct. Copy of database layout attached -
Django file upload get data and store in database
I am new to Django and would like to seek advise regarding file uploads. The user can upload multiple files, but I do not wish to store the files in the database. I just want to get the data from the files and store the data in the database. Is there a way to do it? Is storing the files locally the way to do it? I have seen ways to temporarily store the files locally (but I have seen examples where we need to specify our own (computer) path which may be different for different computers). Is there a way to specify a path where any computers can store the files locally? Apologies that there is no code as I am still thinking how am I going to do it. -
show different content based on logged in user django
So I just learned Python/Django last weekend. What I'm trying to do is have url routes available with different content depending on who's logged in. So my usecase is I create 5 usernames/passwords and then those 5 users can login to read specific content/routes catered to them that no other user should be able to see. Right now I have these routes with correlating views. urlpatterns = [ url(r'^$', accounts.views.loginview), url(r'^accounts/', include('accounts.urls')), url(r'^sitepages/', include('sitepages.urls')), ] I get the auth thing, I'm filtering content to only logged in users using @login_required, it looks like this : from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def attributes(request): return render(request, 'sitepages/something.html') I've researched how to have a different menu bar depending on the user, etc. But I haven't been able to find how to have entirely different routes and content pages depending on the user. I think I'll need to do this using groups in Django and I think that I'll need to use the user's foreign key in order to cater the content. I created one group using admin, but I'm having a hard time consolidating my next step. These are the resources I've checked out: Django Database routing based on … -
Django extend base Field Class
Basically, I want to add a new Field Option as in here https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-options An optional parameter called 'js_inputmask' that is just a string that will be used by a javascript library, for example : class MyModel(models.Model): phone = models.IntegerField(verbose_name='Phone Number', js_inputmask='(99) 9999-9999') How can I add such? I've heard of monkey patch but not sure how to do it in constructors -
Migrating from django user model to a custom user model
I am following these two references (one and two) to have a custom user model in order to authenticate via email and also to add an extra field to it. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) mobile_number = models.IntegerField(unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() ... ... class Meta: db_table = 'auth_user' ... ... As you can see, I have added the db_table='auth_user' into the Meta fields of the class. Also, I have included AUTH_USER_MODEL = 'accounts.User' and User model app (i.e., accounts)into the INSTALLED_APPS in settings.py. Further more, I deleted the migrations folder from the app. Then tried migrating: $ python manage.py makemigrations accounts Migrations for 'accounts': accounts/migrations/0001_initial.py: - Create model User $ python manage.py migrate accounts Which gives me an error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. How can I migrate from the existing django user model into a custom user model? -
How can I access quantity of individual items in my html?
This is my models.py I think I need to add another field in Cart method. Can I do it without altering my models. If no then how should I improve my model models.py from decimal import Decimal from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save, post_save, post_delete from products.models import Variation # Create your models here. class CartItem(models.Model): cart = models.ForeignKey("Cart") item = models.ForeignKey(Variation) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __unicode__(self): return self.item.title def remove(self): return self.item.remove_from_cart() def cart_item_pre_save_receiver(sender, instance, *args, **kwargs): qty = instance.quantity if qty >= 1: price = instance.item.get_price() line_item_total = Decimal(qty) * Decimal(price) instance.line_item_total = line_item_total pre_save.connect(cart_item_pre_save_receiver, sender=CartItem) def cart_item_post_save_receiver(sender, instance, *args, **kwargs): instance.cart.update_subtotal() post_save.connect(cart_item_post_save_receiver, sender=CartItem) post_delete.connect(cart_item_post_save_receiver, sender=CartItem) class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) items = models.ManyToManyField(Variation, through=CartItem) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=25.00) tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.145) tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=25.00) total = models.DecimalField(max_digits=50, decimal_places=2, default=25.00) def __unicode__(self): return str(self.id) def update_subtotal(self): print "updating..." subtotal = 0 items = self.cartitem_set.all() for item in items: subtotal += item.line_item_total self.subtotal = "%.2f" %(subtotal) self.save() def do_tax_and_total_receiver(sender, instance , *args, **kwargs): subtotal = Decimal(instance.subtotal) tax_total = round(subtotal * … -
Django REST Framework serializers: readable and kinda writable
These Django REST Framework serializers sure can be puzzling. I have a situation which I already resolved, but was left wondering if the solution I pulled off really is the smoothest one. I have some product information in my database. As usual, a product is referred to with a product ID. I of course want product IDs to be readable, so I implement a ModelSerializer that has read_only_fields = ('id',) These IDs and other product information is then passed as JSON to the frontend. What I don't want to happen is that unknown people on the internet are able to send me arbitrary product IDs and other information and put these into my database, so that's why I make the field a read_only_field. However, I do want to be able to receive valid, existing product data from the frontend and deserialize it to a Python object. Because the ID field is a read_only_field, DRF ignores it and the ID never gets deserialized. So I guess I kinda want these serializers to be writable, too. Just not... too writable. What I did now is I kinda made an intermediary ProductSerializer that's both readable and writable and that'll never get saved to … -
Changing the name of automatic primary key field in Django
By default, Django gives each model the following field: id = models.AutoField(primary_key=True) (https://docs.djangoproject.com/en/1.10/topics/db/models/#automatic-primary-key-fields) This is great and convenient. However, I would like to know whether it is possible to change the name of the id field to more informative name, e.g., item_id. If this is indeed possible, how can I do that? My model has many classes, and I think that it will be clearer to give more informative field names. Does it really matter? -
Django CreateView success message not shown
I have a CreateView and an UpdateView with success messages in both. But, only the UpdateView success message works and the CreateView message isn't show. Why is this happening? from django.contrib.messages.views import SuccessMessageMixin class CreateRedirect (CreateView): model = MarketingRedirect template_name = 'marketing_redirect/create_redirect.html' success_url = reverse_lazy('backend_redirect') fields = ['redirect_from', 'redirect_to'] success_message = "Redirect successfully created!" class EditRedirect(SuccessMessageMixin, UpdateView): model = MarketingRedirect fields = ['redirect_from', 'redirect_to'] template_name = 'marketing_redirect/edit_redirect.html' context_object_name = 'redirect' success_url = reverse_lazy('backend_redirect') success_message = 'Review successfully updated' -
Django , Postgres : ValueError: invalid literal for int() with base 10: ' '
I am trying to code to webscrap some number. I get everything going well if I try to print it on the window. The print works fine. But After I add the code to save the data into the database( postgres ) I get this error:"ValueError: invalid literal for int() with base 10: ' '" Models.py: from django.db import models class Category(models.Model): name = models.CharField(max_length=128, unique=False) def __unicode__(self): return '%s' %(self.name) class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) price = models.DecimalField(decimal_places=3, max_digits=8) ann_hea = models.CharField(max_length=128, default='ann_headlines') ann_date = models.CharField(max_length=128, default ='ann_date') ann_det = models.CharField(max_length=128,default = 'ann_details') ann_ty = models.CharField(max_length=128, default='ann_type') multi = models.IntegerField(default=0) ex_da = models.CharField(max_length=128, default='date') def __unicode__(self): return self.title ========================================= "views.py" from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.shortcuts import render from rango.models import Category from rango.models import Page from rango.forms import CategoryForm ''' Code for form here....... ''' ''' getFeedContentCA(web): code to scrape web .. posting the last half for the code.. . . . . . xyz = {'Title': x['Company Name'],'price': (x['Price']),'headlines':an_headlines,'Details':an_det,'type': an_ty,'multi': an_multi,'ex_da':an_ex_da,'date':an_date} return xyz y = getFeedContentCA('https://finance.yahoo.com/') print (' _________________________________________ ') print (y['Title']) print (y['price']) print (y['hea']) print (y['Det']) print (y['ty']) print (y['multi']) … -
Get queryset date rage
I have 2 fields for start date and end date. How to get a rows that falls between the start and end dates. That my model class Shop(models.Model): time_begin = models.TimeField(max_length=255, verbose_name=u'Время начала работы') time_end = models.TimeField(max_length=255, verbose_name=u'Время окончания работы')