Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Record created by class in django models not getting recorded in mysql table
I created a table class in models.py in my django app. When I did the migration (into mysql), everything worked ok. I checked the mysql database and there are tables from django. One of the table is derived from the class that I created in models.py in django. I checked the structure of this mysql table, and it matches the attributes in my class. Now I activate the django shell: $python manage.py shell I imported the class and created an instance. >>> from tsts.models import Qstns >>> Qstns.objects.all() [Qstns is my class which represents the mysql table) I get an empty set above, as there are no records. Next I created an instance of this class Qstns, hoping that one record would be appended to my linked mysql table. >>> q=Qstns(question='What is the capital of Australia?', subject='GK', topic='Countires', a='Sydney',b='Canberra',c='Melbourne',d='Brisbane',e='Adelaide',ans='b') >>> q.save These execute without any message. Next I checked the id >>>q.id I do not get anything. It is expected to give me: 1. It looks like database table has not received this record. >>>q.ans It correctly gives me: 'b' I logged into mysql and checked the linked table. It has not received the record. Am I missing something here? … -
How to do field validation in django-import-export for .xls file
I am using Django import and export and importing data from .xls file and now I want to validate the col 2 value should not be empty for that I have used the below code but it is working for the admin site and not for data which is uploaded from an external file. class CTSResource(resources.ModelResource): class meta: Model=CTA def before_import(self, dataset, using_transactions, dry_run, **kwargs): for col in dataset: if col[2] == '': raise ValidationError('This field black. ' 'Error in row with id = %s' % col[2]) How to apply this validation at .xls file level. Is it possible to check at the file processing level here is my upload view code. def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded Successfully...') except: messages.info(request,'Same Email ID has been observed … -
Django: Please correct the errors below
This is my first project with Django and I need help how to fix the error. I want to have a dropdown menu to select in the first field the day, and into the second field to select the month. I can display them, however, I'm getting errors when I try to create an event. Any help is appreciated! from django.db import models from datetime import datetime # Create your models here. class Event(models.Model): title = models.CharField(max_length=200) months_of_year = ((0, 'January'), (1, 'February'), (2, 'March'), (3, 'April'), (4, 'May'), (5, 'June'), (6, 'July'), (7, 'August'), (8, 'September'), (9, 'October'), (10, 'November'), (11, 'December')) days_of_month = ((1,1), (2,2), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (10,10), (11,11), (12,12), (13,13), (14,14), (15,15), (16,16), (17,17), (18,18), (19,19), (20,20), (21,21), (22,22), (23,23), (24,24), (25,25), (26,26), (27,27), (28,28), (29,29), (30,30), (31,31)) month = models.CharField(max_length=10, choices=months_of_year) days = models.CharField(max_length=10, choices=days_of_month) description = models.TextField() is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) def __str__(self): return self.title -
How to remove unneccesary fields and add new fields to django's User model?
I am creating a chatting application in django and started making the models first. I have created a Profile model for users. users/models.py from django.db import models from django.contrib.auth.models import * # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING, related_name='user_profile') name = models.CharField(max_length=25) photo = models.ImageField(upload_to='profile/photos/', blank=True, null=True) about = models.CharField(max_length=140, null=True, blank=True) qr_code = models.ImageField(upload_to='profile/qr_codes/', blank=True) phone_no = models.CharField(max_length=15) is_verified = models.BooleanField(default=False) def __str__(self): return self.name class Meta: db_table = 'cb_profile' verbose_name = 'user profile' verbose_name_plural = 'user profiles' I want to remove the unneccessary fields from User model i.e username, email, first_name and last_name and extend it with the fields present in Profile model the as I am going to do the authentication using the phone_no. I don't know how to do the following changes. Any help would be appreciated. Thanks in advance. -
Django DetailView: related objects
Got 4 Models: models.py class Buildings(models.Model): name = models.CharField(max_length=25) class Zones(models.Model): name = models.CharField(max_length=25) class Departments(models.Model): name = models.CharField(max_length=25) zone = models.ForeignKey(Zones, related_name='departments') class Rooms(models.Model): name = models.CharField(max_length=25) department = models.ForeignKey(Departments, related_name='rooms') building = models.ForeignKey(Buildings, related_name='buildings') What I'm trying to do is: Create DetailView of a Buildings in which we see: departments inside the building rooms inside the building zones each room belongs to Now in views.py I have: class BuildingsDetailView(DetailView): model = Buildings def get_context_data(self, **kwargs): context = super(BuildingsDetailView, self).get_context_data(**kwargs) context['Rooms'] = Rooms.objects.filter(building=self.get_object()) context['Zones'] = Zones.objects.filter(departments__rooms__buildings=self.get_object()) return context detail.html In DetailView I can now access Rooms, Departments and Zones but I'cant match Zones to Rooms. It prints buildings and rooms with departments correctly, then multiplies it with all Zones in building. {% for rm in Rooms %} {% for zn in Zones %} <p> {{ rm.name }} </p> <p> {{ rm.department }} </p> <p> {{ zn.name }} </p> {% endfor %} {% endfor %} Output: Room 1 Depart A Zone 1 Room 1 Depart A Zone 2 etc. How can I match Zone name to corresponding Department of each Room in a Building correctly? Room and Depart name is matched correctly. -
Update updated_at field when foreign keys change
I have a model called Questionnaire. I also have a Question model which has a foreign_key to Questionnaire. When a Question instance that belongs to a Questionnaire instance (via foreign_key) is UPDATED, I need to update the updated_at field on Questionnaire too. How could I do this? -
How to handle validity based permission in Django
In my Django application users have access based on the subscription plan they opt-in, let's say I have a plan called Project Lite, whenever user purchase the plan I will be adding the user to a group called Lite which has a set of permission, such can_add_attachment. In my views, I will check permission like user.has_perm('can_add_attachment'). which works fine, but the problem is Project Lite plan is valid for 1 year after that user will not be allowed to access the view, how to handle this scenario -
Django '>' not supported between instances of 'float' and 'NoneType'
I'm creating a site where users can bid on items, similar to ebay. For the actual view to allow them to bid (put a dollar amount in a form) I am having trouble getting the number to save. Currently though I'm getting a type error: '>' not supported between instances of 'float' and 'NoneType' I have tried doing int(float(my code)) but I'm not sure how to convert it into an int. I have tried many different ways but always get an error. If anyone can help me with the code I'd really appreciate it. I'm very new to Django. Views.py def new_bid(request, listingid): if request.method == "POST": listing = Listings.objects.get(pk=listingid) response = redirect("listingpage", listingid=listingid) try: bid = int(request.POST["bid"]) except ValueError: response.set_cookie( "message", "Please input something before submitting the bid", max_age=3 ) return response if bid > listing.current_price(): response.set_cookie("message", "Your bid was accepted", max_age=3) Bid.objects.create(bid=bid, listing=listing, user=request.user) else: response.set_cookie( "message", "Your bid should be higher than the current bid", max_age=3 ) return response else: return redirect("index") models.py class Listings(models.Model): listingid = models.IntegerField(blank=True, null=True) starting_bid = models.IntegerField() bids = models.ManyToManyField('Bid', related_name='bids_in_the_auction', blank=True) last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, related_name='last_bid_for_the_auction', blank=True, null=True) def current_price(self): return self.listing_for_bid.last().bid class Bid(models.Model): user = models.CharField(max_length=64) title = models.CharField(max_length=64) bid … -
Django annotate(Count('id')) gives wrong answer
I have following models class TagCategory(models.Model): name = models.CharField(max_length=20) class Tag(models.Model): name = models.CharField(max_length=10) category = models.ForeignKey(TagCategory, on_delete=models.CASCADE, related_name='tag') class Position(models.Model): name = models.CharField(max_length=20) class Evaluation(models.Model): position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='evaluations') tags = models.ManyToManyField(Tag, related_name='evaluations') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) text = models.TextField() When I run following script in django shell, pos = Position.objects.annotate(tag=F('evaluations__tags'), tag_category=F('evaluations__tags__category'), tag_cnt=Count('tag')) subquery = pos.filter(id=OuterRef('id'), tag_category=OuterRef('tag_category')).order_by('-tag_cnt')[:3].values('tag') qs = pos.filter(tag__in=Subquery(subquery)) for item in qs.values(): print(item) it gives result like following, for example. {'id': 1, 'name': 'Director', 'tag': 8, 'tag_category': 2, 'tag_cnt': 4} {'id': 1, 'name': 'Director', 'tag': 5, 'tag_category': 1, 'tag_cnt': 1} {'id': 1, 'name': 'Director', 'tag': 7, 'tag_category': 1, 'tag_cnt': 3} {'id': 1, 'name': 'Director', 'tag': 9, 'tag_category': 2, 'tag_cnt': 2} qs gives what I wanted, but the problem rises if I annotate count of rows per id to qs. When I run following, final = qs.values('id').annotate(cnt=Count('id')) final gives <QuerySet [{'id': 1, 'cnt': 10}]> which is not what I have expected. I hope cnt give '4' for this example. How should I change my orm code? -
Why does this error occur when I try to save a record of my sale in the database?
I am trying to save the details of the sale in the respective tables of the DB, however I get this error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 'id_cliente' Previously, another error related to ajax appeared, which was fixed by adding a few lines of code. But when I started modifying the post method and thus sending the data, it generated this error. I hope you can help ... I need to move forward: / Views elif action == 'add': ventas = json.loads(request.POST['ventas']) venta = Venta() venta.id_cliente = ventas['id_cliente'] venta.id_empleado = ventas['id_empleado'] venta.fecha_venta = ventas['fecha_venta'] venta.forma_pago = ventas['forma_pago'] venta.precio_total = float(ventas['precio_total']) venta.save() for i in ventas['productos']: detalle_venta = Detalle_Venta() detalle_venta.id_venta = venta.id_venta detalle_venta.id_producto = i['id_producto'] detalle_venta.cantidad = int(i['cantidad']) detalle_venta.subtotal = float(i['subtotal']) detalle_venta.save() JS $('form').on('submit', function (e) { e.preventDefault(); ventas.items.id_cliente = $('input[name="id_cliente"]').val(); ventas.items.id_empleado = $('input[name="id_empleado"]').val(); ventas.items.fecha_venta = $('input[name="fecha_venta"]').val(); ventas.items.forma_pago = $('input[name="forma_pago"]').val(); ventas.items.precio_total = $('input[name="precio_total"]').val(); var parametros = new FormData(); parametros.append('action', $('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); enviar_productos(window.location.pathname, parametros, function () { location.href = 'crear_venta'; }); }); Models class Venta(models.Model): id_venta = models.AutoField(primary_key=True) id_cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE,blank=True, null=True) id_empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE,blank=True, null=True) fecha_venta = models.DateField(default=datetime.now) forma_pago = models.ForeignKey(Metodo_Pago, on_delete=models.CASCADE) precio_total = models.DecimalField( default=0.00, max_digits=9, decimal_places=2) class Detalle_Venta(models.Model): id_detalle_venta = … -
How to access Django settings file from template [duplicate]
Is there any way I can change the parameters mentioned in django settings from a template. I want to change the api keys from template STRIPE_PUBLIC_KEY = 'string' or is there a way to store it in safe place and editable from template, any help is appreciated -
Django website with machine learning + AWS
I am a newbie on AWS and wanted advice on which Amazon web services to use. I am doing a website with Django/Python, that gives the result of a machine learning model. The data would be imported by API, stored into an S3/RDS bucket. The ML model would run just once a month, the computation normally lasts 3h with 16 gb of RAM. I also need something to orchestrate, like run the model each 40 days. I am wondering which solution to use, between maybe Beanstalk, Lightsail, or Lambda (or something else maybe). I need the website to be accessible at any time, but also need to run this model for cheap (comp. on demand), and nothing stored on my personal computer if possible. Any recommendation please? -
How can I enable the user to download a file from a server using django?
Apologies first. I am not quite certain as to how to phrase my question. The thing is this. I am using django 3.1.2 to build a website, and I want the user of my website to be able to download a .zip file created at the backend when they click a button in the web page. However, when testing, I found that the downloading would not start when click the button. No error was thrown either, and I just could not work out where I erred. javascript: document.querySelector("#download").onclick = function() { // #download is the button I am talking about; it is in reality a div element var formData = new FormData(); for (let i = 2; i < formElementsNumber; i++) { let element = formElements[i]; formData.append(element.name, element.value); } formData.append("txtFile", formElements[1].files[0]); formData.append("token", token); // Up to here, everything works fine $.ajax({ url: "/download/", type: 'post', data: formData, // Essential; otherwise will receive an "illegal invocation" error contentType: false, processData: false, success: function(data) { // What should I add here to make the downloading start? } }) } urls.py: urlpatterns = [ path('', views.index), path('process/', views.process), path('download/', views.download) ] views.py: def download(request): // Creates an .zip file property_list = ['imageWidth', 'imageHeight', … -
Django how to mark user-specific objects in queryset to be sent to template?
A newbie in the world of Django. I have what seems to be a general problem but I couldn't find a good answer on the Internet.I need to pass a django queryset to template to display a list. Of those Article objects, some may have been written by the user, I want to highlight/star those particular articles. What is the best practice/solution to achieve this? for example: class Article(models.Model) : article_text = models.CharField(max=32) written_by = models.CharField() So I can access the list of all articles in the views.py: article_list = Articles.objects.all() And I can filter all the articles by my current logged in user as my_article = article_list.filter(written_by=current_user) Within Template I want to display a list of all articles, but 'star' only the ones which have been written by the current logged in user so in my template I want to do something like this: {% for article in article_list %} {% if article.some_flag %} Starred Article {% endif %} {% endfor %} Question: Is there a good way to annotate 'article_list' objects with a flag some_flag that marks 'my_articles' in views.py? Or is there a way to do this within template by passing both article_list and mylist and doing … -
delete comments with the user
I am using the comment library. It is built on top of django-contrib-comments The question is, how can you make sure that when you delete a user, all comments associated with him would be deleted? I would be grateful for any help -
Django REST Framework throttling / authorization with React or other front-end JS library
Django REST framework has a throttling feature https://www.django-rest-framework.org/api-guide/throttling/ Understand that with throttling can limit unauthorized users browsing my app but endpoints of REST are publicly visible for example: https://exampledomain.com/api/v2/courses/ - this would be example endpoint Do I setup Django REST with token or any other authorization and then save that token in env variables (config variables) that app can use that and be authorized or what is the proper way to handle that - can you point me to right direction somehow - what I am trying to accomplish is that nobody can take the endpoints and try to post things agains them, only web application is allowed to do that and meaning not only POST but as GET and other requests. -
Django Keycloak - Remove username field from the insert query to client after user registration
Using email as a validation method in Keycloak, do I have an option (maybe with mappers, but I tried) to take away the username field from the insert query is sent to the client after user registration? I could apply a workaround to define a username field in the client side model, but I would like to fix this issue from the keycloak side. Thank you, I appreciate Mariano -
Heroku app: ModuleNotFoundError: No module named 'pwa'
I am trying to deploy my app to heroku and I keep getting this error even though when I run locally it works perfectly fine. I have added django-pwa==1.0.10 to my requirments.txt file also so that heroku installs the package. Here are my installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pwa', # 'embed_video', 'whitenoise.runserver_nostatic', 'courses.apps.CoursesConfig', 'accounts.apps.AccountsConfig', 'announcements.apps.AnnouncementsConfig', 'students.apps.StudentsConfig', 'home.apps.HomeConfig', 'event_calendar.apps.EventCalendarConfig', ] Here is my directory Not really sure what to do as I am not very experienced with heroku. -
Django migration from Foreign key to Integer field error occured
I'm facing an issue migrating my django models, when converting the foreign key to normal integer field. Here you are my code below. Old migration data type: bank_id = models.ForeignKey(Bank, related_name='bank', on_delete=models.CASCADE, blank=True,null=True) New migration data type: bank = models.IntegerField(default=0, null=True, blank=True) **The error that I got from the migration. return int(value) ValueError: invalid literal for int() with base 10: ''** Any idea, how I can convert the existing data in the table? -
How can I create admin-like look for the whole page in Django?
I am creating small web-application using django, which needs to have 4 different levels of access. I have created models and Admin page does 80% of what I would have expected (for most privileged user which is Admin), and I really like the default admin look of the page. I am unsure whether I should just extend Admin view, but I wish to use the default UI for all users (with small changes like different colors or navbar related to their level of access) - how can I do it? Can I use default templates/views of models and slightly change them/add new ones based on them without simply extending Admin view? I am new to web applications and I am currently stuck. Tl;dr how can I keep default UI for the whole page -
Form can't assign to function call
Flight funtion doesn't return from models in view. I changed models from null=True to nothing. Is the problem within my return code or is it something else? The thing is nothing gives an error other than views which is weird. def add_flight(request): if request.method == 'POST': form = FlightForm(request.POST) if form.is_valid(): a = Flight(departing_date=form.cleaned_data["departing_date"], deptAirport=form.cleaned_data["deptAirport"], arrAirport=form.cleaned_data["arrAirport"], duration=form.cleaned_data["departing_date"], airline=form.cleaned_data["airline"], price=form.cleaned_data["price"], deptCity=form.cleaned_data["deptCity"], arrCity=form.cleaned_data["arrCity"], deptHour=form.cleaned_data["deptHour"], , arrHour=form.cleaned_data["arrHour"]) a.save() #return HttpResponse("Success!") return HttpResponseRedirect('/flights/') else: form = FlightForm() return render(request, 'add_flight.html', {'form': form}) It can't return Flight model from models which looks like this class Flight(models.Model): departing_date = models.CharField(max_length=10) deptAirport = models.CharField(max_length=100) arrAirport = models.CharField(max_length=100) duration = models.CharField(max_length=5) airline = models.CharField(max_length=20) price = models.CharField(max_length=100) deptCity = models.CharField(max_length=100) arrCity = models.CharField(max_length=100) deptHour = models.CharField(max_length=4) arrHour = models.CharField(max_length=4) def __str__(self): return self.departing_date+" "+self.deptAirport+" "+self.arrAirport+" "+self.duration+" "\ +self.airline+" "+self.price+" "+self.deptCity+" "+self.arrCity+" "+self.deptHour+" "+self.arrHour Any suggestions? -
Django do not allow another like is user already liked post
I want to allow an user to be able to like an post only once. Here is my code so far: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.PositiveIntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) In views.py: def LikePostView(request, pk): post = get_object_or_404(Post, pk=pk) post.likes = post.likes+1 post.save() return render(request, 'blog/like_done.html') Code to like a post on frontend: <p class="content">{{ post.likes }} likes</p> {% if user.is_authenticated %} <a href='{% url "like_post" post.id %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a> {% else %} <a onclick="alert('In order to like a post, you must be logged in!')" href='{% url "blog-home" %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a> {% endif %} And like_done.html: {% extends "blog/base.html" %} {% block content %} <h2 class="alert alert-success">Post Liked Successfuly!</h2> <br> <a class="btn btn-success" href="{% url 'blog-home' %}">Go Back Home?</a> <br> {% endblock content %} So with all this, how would I make the user be allowed to only like a post once. I am only beginner, so please explain a little. -
Update dynamic choices when object is created in Django
I have a few different apps inside of my Django (3.1.1) project. Each of them contains at least one field that shows a dropdown of the objects below it. When I create a lower level object, the drop down lists don't reflect the new object until I stop and then restart the server. I just want to know how I could do this automatically. I've tried to override the save() function (see below), but it hasn't worked. Not sure if I'm doing it wrong, or I need to try something else. Additional (but related) question...how can I make this fix for when objects are deleted, too? Do I need to write in two separate fixes, or is there just one that I can do that will basically handle repopulating the dropdowns any time an object is either created or deleted? Thanks for any help! The code/pseudo code: NOTE: I'm slimming this down for simplicity (I hope). There are many fields in each app, but I'm just going to list the one that pertains to the dropdown. **PAGE APP** page_number = .... .... def save(self, *args, **kwargs): Book.pages = Library.pages = models.CharField(choices=create_pages_choices(), max_length=15, null=True) super(Page, self).save(*args, **kwargs) **BOOK APP** pages = … -
(class_='result_price') that's can be useful anytime?
soup = BeautifulSoup(data, 'html.parser') post_listings = soup.find_all('li', {'class': 'result-row'}) post_title = post_listings[0].find(class_='result-title').text post_url = post_listings[0].find('a').get('href') post_price = post_listings[0].find(class_='result_price').text -
Displaying form errors with Materializecss and Django
I'm using materializecss (django-materializecss-form) to display my forms. <!-- form.hmtl --> {% extends "market/base.html" %} {% block content %} {% load materializecss %} <form method="POST" enctype="multipart/form-data"> <!-- ... --> <div class="row"> {{ form.description|materializecss:'s12, icon=flag' }} {{ form.description.errors }} </div> <div class="row"> <label>Kategorie</label><br/> {{ form.category }} {{ form.category.errors }} </div> <!-- ... --> </form> The description works well. The »categories« are displayed in a grouped select field. Thus, I cannot use the filter |materializecss for this field. Otherwise the grouping would not work. # models.py class SmallAd(models.Model): # ... category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Kategorie') description = models.TextField(verbose_name='Beschreibung') # ... However, the main problem is that the errors ('field must be filled') are not displayed in those grouped select-fields as long as I do not use the materializecss-filter. But I need both the error-messages and the grouping. Has anybody a good idea to solve this?