Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django jumping model id number (AutoField)
Today my django app jumped from id 126 to 1125 in one of my models, 999 ids! Does anybody knows what could cause it? See below the screenshot of my admin area, from my MSSQL database and also my model code: I appreciate any feedback that might help me to understand why django did it... DJANGO ADMIN: MSSQL: MY MODEL: (which is working for many months without issues... Also, as you can see, the id is an AutoField, it is not in my class, only on the migrations file.) class New_ticket(models.Model): process_expert = models.ForeignKey(Team_Structure, on_delete=models.SET_NULL, limit_choices_to={'available':True}, blank=True, null=True) status = models.ForeignKey(Status_table, on_delete=models.CASCADE, limit_choices_to={'available':True}, blank=True, null=True) created_by = models.CharField(max_length=20) created_on = models.DateTimeField() option = models.ForeignKey(Options_table, on_delete=models.CASCADE, limit_choices_to={'available':True}, verbose_name="Where is the issue?") priority_level = models.ForeignKey(Priority_level, on_delete=models.CASCADE, limit_choices_to={'available':True}) department = models.ForeignKey(Department, on_delete=models.CASCADE, limit_choices_to={'available':True}) transaction = models.CharField(max_length=50, blank=True) zone = ChainedForeignKey(Zone,chained_field="option",chained_model_field="option", show_all=False, auto_choose=True, sort=True, blank=True, null=True) duration_of_error = models.CharField(max_length=50, blank=True) error_message = models.TextField(max_length=250) comments = models.TextField(blank=True) upload_1 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) upload_2 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) upload_3 = models.FileField(upload_to='uploads/', blank=True, validators=[file_size]) history = HistoricalRecords() def __str__(self): return str(self.id) class Meta: verbose_name_plural = "Tickets" -
generate unique id in each loop of for loop django template
I need to generate unique id in each loop instead of ````city-selected``` {% for form in formset.forms %} <tr> {% for field in form %} <td class="input_td{% if field.errors %} error_td{% endif %}"> <select name="city-select" id="city-select"></select> </td> {% endfor %} <td class="delete_formset_td"></td> </tr> {% endfor %} How can I generate it here? -
One To Many and models
i am trying to build my first project, a CRM website to handle orders and inventory. and i got stuck, i was able to link orders to customer. but when i try to build order that contain multi items. for some reason i didn't find a way to do it. hope you can assist me. so I have User>>Order>>Multi Items. questions: 1) does the best practice here is just use ForeignKey ? this my model's code: from django.db import models class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def date_createdview(self): return self.date_created.strftime('%B %d %Y') class Product(models.Model): CATEGORY = ( ('General', 'General'), ('SmartHome', 'SmartHome'), ('Software', 'Software'), ('Mobile', 'Mobile'), ) name = models.CharField(verbose_name='שם', max_length=200, null=True) price = models.FloatField(verbose_name='מחיר', null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY, verbose_name='קטגוריה') description = models.CharField(max_length=200, null=True, verbose_name='מלל חופשי') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('New', 'New'), ('Work in progress', 'Work in progress'), ('completed', 'completed'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def date_createdview(self): return self.date_created.strftime('%d/%m/%Y') class OrderItem(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) order = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=True) 2)how should … -
Execute a Python file via PHP Script
I have a Python script ready which completes some tasks. to initiate the task I need to manually start the Index.py Now I want a web page (php / html or anything) which will execute the index.py located on ec2 and the python code will execute. (no issues if it does not shows output) Also required that the terminal shall not be on every time thus we need to run services in background. Thanks +91 9033024545 -
Django-bootstrap-modal-forms on datatable row click
So, I have datatable, and I need to open modal form whenever a row is clicked. My table is defined like this <table id="tabledata" class="datatable display"> Using django-bootstrap-modal-forms, I've done this: $('.datatable').modalForm({ formURL: "{% url 'myapp:modelform-url' %}" }).on('click', 'tbody tr', function(){ // other code here }) It sort of works, except the modal pops up wherever I click on the table. I tried something like this but doesn't seem to work: $('.tabledata tbody tr').modalForm({}) Any ideas? -
What is the right way to load different js file for each template in Django?
I want to load different .js, .css files (static files) for each template, but also to load same group of files for each of them. Example: first.html - Here I want to load jquery.js, jquery.css, maps.js second.html - Here I want to load jquery.js, jquery.css without maps.js third.html - Here I want to load test.js, maps.js Right now I add all files in footer.html (.js files), or header.html (.css files) and include all of them, via {% include 'footer.html' %} -
Average for ratings in Django
I working on an app using django and python at school. It an app for writing reviews and rating movies. I would like to implement a rating system, so I can display the average rating for a film based on the rating given in the reviews. At the moment this code gives the rating in descending order for all reviews, and not the average. Like if I got two reviews for a movie, with score 1 and 5, I get both, but not one that says 3. Please help! In models.py: class Film(models.Model): title = models.CharField(max_length=100) title_short = models.CharField(max_length=17, default=None, null=True) plot = models.TextField() poster = models.ImageField(default="default.png", upload_to="posters") release_date = models.DateField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) class Review(models.Model): writer = models.ForeignKey(User, on_delete=models.CASCADE) reviewed_film = models.ForeignKey(Film, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() rating = models.IntegerField( default=1, validators=[MinValueValidator(1), MaxValueValidator(5)] ) In views.py: class ToplistListView(LoginRequiredMixin, ListView): model = Review template_name = "board/toplist.html" context_object_name = "films" def get_queryset(self): return Review.objects.annotate(avg_rating=Avg('rating')).order_by('-avg_rating') -
Celery after_task_publish signal fire but other signals do not?
I have the following three signal handlers: @after_task_publish.connect def task_sent_handler(sender=None, headers=None, body=None, **kwargs): info = headers if 'task' in headers else body logger.info('task_sent_handler for task id {info[id]}'.format( info=info, )) @task_success.connect def task_success_handler(*args, **kwargs): logger.info('task_success_handler') @task_failure.connect def task_failure_handler(*args, **kwargs): logger.info('task_failure_handler') The three handlers are registered in django app ready method: def ready(self): import app.signals Celery broker (redis) run locally, and the tasks are applied async using delay. I can only see in the log file the task_sent_handler handler, but the other handlers does not log, any idea why? I also tried task_prerun, but it did not fire also. -
Every task failing to execute on Google Cloud Tasks
I need to run some asynchronous tasks in a Django app, and I started to look into Google Cloud Tasks. I think I have followed all the instructions - and every possible variation I could think of, without success so far. The problem is that all created tasks go to the queue, but fail to execute. The console and the logs report only a http code 301 (permanent redirection). For the sake of simplicity, I deployed the same code to two services of an App Engine (standard), and routed the tasks request to only one of them. It looks like the code itself is working fine. When I go to "https://[proj].appspot.com/api/v1/tasks", the routine executes nicely and there's no redirection according to DevTools/Network. When Cloud Tasks try to call "/api/v1/tasks", it fails every time. If anyone could take a look at the code below and point out what may be causing this failure, I'd appreciate very much. Thank you. #-------------------------------- # [proj]/.../urls.py #-------------------------------- from [proj].api import tasks urlpatterns += [ # tasks api path('api/v1/tasks', tasks, name='tasks'), ] #-------------------------------- # [proj]/api.py: #-------------------------------- from django.views.decorators.csrf import csrf_exempt @csrf_exempt def tasks(request): print('Start api') payload = request.body.decode("utf-8") print (payload) print('End api') return HttpResponse('OK') #-------------------------------- # … -
Django how to create multiple model objects at once - sharing all values but one
I have been making an app for tracking user wages and issues that they are working on. I would like to have a view from which I could specify payment details and select mutliple Users to whom the payment will be made. I have a User model and Payment model. In the Payment model there is a FK to Users. Is there a way to have a view where I'll select multiple Users, fill the other shared vlaues (such as date, value etc.) in the form and then hit submit. I'm looking for a way to override class based functions so that it iterates through the multiple select field (bunch of User ids) and then creates and saves Payment model object with the FK and shared fields. Thank you very much. -
Django button that updates text from database with each press
I am trying to make a basic quizz type app in Django and I'm having a problem with understanding how Django works and where to find instructions to this specific problem. Below is the functionality that I am looking for: -A view that has a quizz question text that comes from a database -An answer text field to that quizz -Pressing enter after typing or pressing a submit button changes the quizz question to the next question from the database Any help on this would be much appreciated. -
get students in a course in django
i'm pretty new to django and i'm struggling with models and database but i managed to get some stuff right but this here isnt working out for me. so basically what i want to do is when i click on a course it shows me a table with the students who are registered to this course but i keep getting an empty table models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.text import slugify User = get_user_model() # Create your models here class student (models.Model): S_id = models.IntegerField(unique=True) S_fname = models.CharField(max_length=255) S_lname = models.CharField(max_length=255) def __str__(self): return self.S_id class classes(models.Model): C_id = models.CharField(max_length=255,unique=True) C_name = models.CharField(max_length=255) C_room = models.CharField(max_length=255) Start_time = models.CharField(max_length=255) Instructs = models.ManyToManyField(User, through='Teaches') Registered = models.ManyToManyField(student, through='Registered') slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.C_id def save(self,*args,**kwargs): self.slug = slugify(self.C_id) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('classes:single',kwargs={'slug':self.slug}) class Meta: ordering = ['C_name'] class Teaches(models.Model): Instructor = models.ForeignKey(User, related_name='St_id', on_delete=models.CASCADE) Course = models.ForeignKey(classes, related_name='Co_id', on_delete=models.CASCADE) class Registered(models.Model): Student = models.ForeignKey(student, related_name='Stu_id', on_delete=models.CASCADE) Course = models.ForeignKey(classes, related_name='Cou_id', on_delete=models.CASCADE) classes_detail.html {% extends "classes/classes_base.html" %} {% block pregroup %} <div class="container"> <h1>{{classes.C_name}}</h1> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Student ID</th> <th>Student First Name</th> <th>Student Last Name</th> <th>attendance</th> … -
how to identified two login that this is loader and other is driver in django project
I am working on a Django project where a user post a load and driver take that load and to deliver to the destination . My point is how I can differentiate both of them in my project like when someone login whether is loader or driver because when driver login the all the post created by multiple users will display and on the other hands the loader will see his own post after login just like in the uber app -
Python Django- How to download file on client machine in django project
I am new to python, I have created a small Django application to download data into excel format. it downloads in a project folder or given path(on the server). but when I hit the URL from the client machine then it should download on the client machine but it downloads on my server only. Please suggest a suitable method(code) to download an excel file on the client machine only. Thanks in advance. -------code------- try: cursor = connection.cursor() cursor.execute("""select * from table""") columns = [desc[0] for desc in cursor.description] data = cursor.fetchall() result = len(data) print("No of records :" ,len(data)) df = pd.DataFrame(list(data), columns=columns) home = os.path.expanduser("~") print('Home path------------',home) download_location = os.path.join(home,'Downloads') print('download path------------',download_location) filename = 'django_simple.xlsx' writer = pd.ExcelWriter(download_location+'/'+ filename) df.to_excel(writer, sheet_name='Hundai') writer.save() print("File saved successfully!") cursor.close() except: print("There is an error") finally: if (connection): connection.close() cursor.close() print("The MSSQL connection is closed") return render(request,'result.html',{'result': result}) -
where are the pages are stored which I created through Django CMS and how can I seperately copy and run it to other PC?
I need to seperately know where are actually the pages are stored which I created through Django CMS. In which directory of venv/site packages/ where it is stored ?. please anyone knows . -
pdfkit image not embedded using Django
I'm converting a protected webpage into pdf using Django and this solution. The solution works great except the part that the webpage contains images which do not show up in the pdf and i get an error Warning: Failed to load file:///media/images/main/logo.jpg (ignore) I'm currently using from_string method as follows pdfkit.from_string(msg_html, 'testing123.pdf') #msg_html contains html string with images -
Django TestCase: GET request should return 404 but return 200 in my test...?
I have a pdf function that print a pdf resume for example, this function is called with url /randomization/pdf/?patient=CIV-TR-001&medicament=8&type=1 if GET parameters are missing or not valid, it return a 404 or 500 error and it is the correct behavior I want to make a test for that but even if I pass empty 'patient' in my test, it always return status_code=200 (/randomization/pdf/?patient=&medicament=8&type=1) wherease when I call this url in my app, I am correctly redirected to my 404 page... I don't understand why url.py app_name='randomization' urlpatterns = [ path('pdf/', views.pdf, name='pdf'), ] views.py @login_required def pdf(request): ... # Données du formulaire de confirmation de randomisation patient = get_object_or_404(Randomisation, ran_num = request.GET.get('patient')) ... if request.GET.get('medicament') == '': med = None else: med = request.GET.get('medicament') dru = get_object_or_404(Medicament, med_ide = med) ... return FileResponse(buffer, as_attachment=True, filename=form + ' ' + pat +'.pdf') test.py class IndexPageTestCase(TestCase): def setUp(self): self.client = Client(HTTP_ACCEPT_LANGUAGE='en') self.pays = Pays.objects.create(pay_ide = 1,pay_nom_eng = 'Ivory Coast',pay_nom_fra = 'Côte d Ivoire',pay_abr = 'CIV') self.region = Region.objects.create(reg_ide = 1,pay = self.pays,reg_nom = 'Region 1',reg_abr = 'RE1') self.site = Site.objects.create(sit_ide = 1,reg=self.region,sit_typ = 'National',sit_nom_eng = 'PACCI',sit_nom_fra = 'PACCI',sit_abr = 'PA') self.user = User.objects.create_user('Slater','slater@surfeur.com','mereva2019') self.profile = Profile.objects.create(user=self.user,site = self.site) self.patient = Randomisation.objects.create(ran_num='CIV-TR-001',ran_dat='2020-03-09',ran_inv='Fanning',ran_pro=1,ran_crf_inc=1,ran_tbc=3,ran_crf_eli=1,ran_cri=1,ran_sta=1,ran_vih=0,ran_bra=4,ran_med='AAA',ran_log_dat=timezone.now(),ran_log_sit='TR') self.medicament … -
How to Delete or Ignore serializer.data object in serializer.py?
I need to delete serializer.data object in serializer, because i'm having some record in my table. But the entire record details is present in other microservice, Once someone called my api i need to call that service to get the data. But if the record is empty, i need to ignore this object. I can do this view, but it's possible to do in Serializer.py. Check the reference code: class CourseSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() def get_user(self, obj): token = self.context['request'].META['HTTP_TOKEN'] username = get_user_details_from_id(str(obj['user']), token, name=1) if username: return username else: obj = {} class Meta: model = Course fields = ('user', 'total_score') I want to ignore the record in SerializerMethodfield if the username is empty -
Is it possible to have default values of TextFields refer to txt files?
I am building a basic system that allows users to send templated emails in Django. I have a field in my email model that provides the content for the email: class Email(models.Model): message = models.TextField(_("Message"), blank=True) I want to specify default content, however the message itself could be quite long. Is there any way to have the default value refer to a text file (or any file) rather than have this in the model itself? E.g. class Email(models.Model): message = models.TextField(_("Message"), blank=True, default='mytextfile.txt') Is much better than class Email(models.Model): message = models.TextField(_("Message"), blank=True, default='"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia ...') -
How to setup connection to MySql database with gitlab CI/CD
I'm trying to set up automatic testing of django project using CI/CD gitlab. The problem is, I can't connect to the Mysql database in any way. gitlab-ci.yml services: - mysql:5.7 variables: MYSQL_DATABASE: "db_name" MYSQL_ROOT_PASSWORD: "dbpass" MYSQL_USER: "username" MYSQL_PASSWORD: "dbpass" stages: - test test: stage: test before_script: - apt update -qy && apt-get install -qqy --no-install-recommends default-mysql-client - mysql --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'" script: - apt update -qy - apt install python3 python3-pip virtualenvwrapper -qy - virtualenv --python=python3 venv/ - source venv/bin/activate - pwd - pip install -r requirement.txt - python manage.py test apps With this file configuration, I get error ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) What have I tried to do add to mysql script tcp connection unstead socket mysql --protocol=TCP --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'" And in this case I got ERROR 2002 (HY000): Can't connect to MySQL server on 'localhost' (99) How do I set up properly? -
generate password when creating a user by HR and send email to the created user to log in ,in django
I am beginner for Django. How can i generate a password and send the generated password to the user with its first name and last name to its email, and make the password field doesn't appear when i create the user through the HR. I also searched on the internet i got some codes and ideas but i don't know when to put them in class based when i inherit the AbstractBase. The code is as follows . but where i am going to put it password = User.objects.make_random_password() user.set_password(password) -
needs to have a value for field "id" before this many-to-many relationship can be used
While using bulk_create for my slots. I am always getting the error : ValueError(u'"<Schedule: 10:00:00, 01:00:00>" needs to have a value for field "id" before this many-to-many relationship can be used.',) The Code I have written is as follows: clients = Client.objects.filter(id__in=client_ids) fromuidaylabels = Label.objects.filter(id__in=label_ids, uidaylabel__isnull=False, datelabelmap__isnull=True).annotate(dayval=F('uidaylabel__day')).values('dayval','client','id') fromdayvals = dict([(e['dayval'], e) for e in fromuidaylabels]) touidaylabels = Label.objects.filter(client__id__in=client_ids, uidaylabel__day__in=fromdayvals.keys()).annotate(dayval=F('uidaylabel__day')).annotate(maxid=Max('id')).values('dayval', 'maxid','client') todayclient = {} for e in touidaylabels: todayclient[e['client']] = todayclient.setdefault(e['client'], []) + [e['dayval']] todayclientstocreate = {} for client_id, dayvals in todayclient.items(): todayclientstocreate[client_id] = list(set(fromdayvals.keys()) - set(todayclient[client_id])) day_slots = Schedule.objects.filter(label__in=[e.get('id') for e in fromuidaylabels]) day_slot_mapping = {} for sc in day_slots: day_slot_mapping[fromuidaylabels.values_list("dayval", flat = True).get(id = sc.label_id)] = day_slot_mapping.setdefault(fromuidaylabels.values_list("dayval", flat = True).get(id = sc.label_id), []) + [sc] for sc in date_slots: date_slot_mapping[fromuidatelabels.values_list("dateval", flat = True).get(id = sc.label_id)] = date_slot_mapping.setdefault(fromuidatelabels.values_list("dateval", flat = True).get(id = sc.label_id), []) + [sc] sc_list = [] for day, slots in day_slot_mapping.items(): for label_details in touidaylabels: label = Label.objects.get(id = label_details['maxid']) client = Client.objects.get(id = label_details['client']) for slot in slots: slot.pk = None slot.client = client slot.label = label sc_list.append(slot) if sc_list: SlotPlAssociation.objects.bulk_create(sc_list) Here the last line 'SlotPlAssociation.objects.bulk_create(sc_list)' pops the error - AttributeError: 'Schedule' object has no attribute 'playlist_id'. I added the other values to the slots, but … -
Django nested objects, different serializers GET and POST
this is a follow-up to this question I had here. I can now POST a new AP object using user Primary Key and after commenting this line in the AP serializer user = UserIndexSerializer(): Postman request: { "user":1, "name":"Max AP 05" } However the problem that I now have is that the initial UserIdexSerializer is rendered useless. This serializer determines the fields to show in a GET request but in consequence imposes the fields required in a POST request. What I'm trying to do is: POST a new AP object only using the user ID Show the UserIndexSerializer fields during a GET request (first_name, last_name, but not the ID) How can I make this work? I have found and read this post. I tried using different views, one for listing my models and one for creating a new one: from rest_framework import serializers from ..models.model_art_piece import AP from .serializers_user import * class APIndexSerializer(serializers.ModelSerializer): user = UserIndexSerializer() class Meta: model = AP fields = [ 'id', 'user', 'name' ] class APCreateSerializer(serializers.ModelSerializer): user = UserIDSerializer() class Meta: model = AP fields = [ 'id', 'user', 'name' ] def create(self, validated_data): ap = AP.objects.create(**validated_data) return ap class APDetailsSerializer(serializers.ModelSerializer): class Meta: model = AP … -
Count List of Objects inside JSONField in Django
class TopCountries(models.Model): top_countries = JSONField(null=True) top_countries is JSONField 'top_countries': [ {'country_code': 'AX', 'country_name': 'Åland Islands'}, {'country_code': 'AL', 'country_name': 'Albania'}, {'country_code': 'DZ', 'country_name': 'Algeria'} ] I am new to advanced queries. I've tried the query below but it does not give me the desired output. Query: UserProfile.objects.aggregate(Count('top_countries')) Output: {'top_countries__count': 1} Desired Output: {'top_countries__count': 3} -
Wagtail large list within stream field block
We use wagtail for our blogs that are part of an eCommerce site. When we want to add a product to the blog as it stands we have to put the exact product name in which then matches on save. As names can change this then breaks that blog which isnt ideal. What we would like to do is add a field to our streamfield block that lets you pick from our list of products, however as we have 200k+ products and there might be up to 20 products on each blog loading the list into a dropdown is no good. What we need is to replicate what we do in Django admin using django-autocomplete-light where you start typing and get results based on that rather than loading the list into the HTML. What we cant work out is how to do that within a streamfield block, I have seen libraries like "Wagtail Autocomplete" however it seems you can only use that as a panel rather than within a block. As far as we can see you can only use sub-classes of wagtail.core.blocks or they dont show up in the interface. Any ideas? Thanks in advance!