Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need advice on implementing feature regarding Django models
I need some kinds of advice. In my models I have teachers, students and courses. Each teacher has its own courses. I was wondering how can I allow students to visualize my courses, as a teacher. In the teacher classroom (teacher control panel), I listed his courses, and near each course I made an enroll students button. So when that is clicked on, it will redirect to the course's slug page and there he will be able to search for his students (like classroom/engineering/enroll). This is what I done so far. Now I was thinking of some kind of boolean value checkbox near each student name and when all desired students are checked, below he will have an Enroll button, which will allow those students to visualize that course page. My problem is, how do I implement this enroll exactly ? What is a good approach ? Please advice me. -
Performance problems while creating multiple objects
My aim is to create a matrix with individual editable fields. Since different people should only be allowed to edit certain fields I thought about creating an object called CellCE and an object level permission. my models.py class CellCE(models.Model): row = models.ForeignKey('Descriptor',related_name='activecell', on_delete=models.CASCADE) col = models.ForeignKey('Descriptor',related_name='passivecell', on_delete=models.CASCADE) val = models.IntegerField(default=0) project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1') #permission for Cells class Meta: permissions = ( ("edit_cellCE", "Has permission to edit value of Cause and Effect cell"), ) @classmethod def create(cls, row, col, project): CellCE = cls(row=row, col=col, project=project) CellCE.save() return CellCE my views.py def phase2(request, id): projectname = get_object_or_404(Project, pk=id) projectid = id project = Project.objects.get (id=projectid) projectdescriptors = Descriptor.objects.filter( project=projectid) for Descriptor.id in projectdescriptors: row = Descriptor.id for Descriptor.id in projectdescriptors: col = Descriptor.id if CellCE.objects.filter(row=row, col=col, project=project).exists(): pass else: obj = CellCE.create(row, col, project) CellCElist = CellCE.objects.filter(project= project) context = {'CellCElist': CellCElist, 'projectname': projectname, 'projectid': projectid, 'projectdescriptors': projectdescriptors} return render(request, 'szenario/phase2.html', context) my template <table> {% for drow in projectdescriptors %} {% if forloop.first %} <tr> <th align="left">Descriptors</th> {% for value in projectdescriptors %} <th>{{value}}</th> {% endfor %} </tr> {% endif %} <tr> <th align="left">{{drow}}</th> {% for dcol in projectdescriptors %} <td align="center"> {% if forloop.parentloop.counter == forloop.counter %} - … -
django query datetime filed issue
i have tried to apply filter datetime filed in django query,but i got result zero the below code i have tried: Customers.objects.filter(created_at__month=1).count() but select id,created_at from customer_customers; +----+----------------------------+ | id | created_at | +----+----------------------------+ | 1 | 2017-12-24 06:54:41.264756 | | 2 | 2017-12-24 07:05:37.317395 | | 3 | 2017-12-24 10:05:29.957158 | | 4 | 2017-12-29 13:30:21.572926 | | 5 | 2017-12-29 13:58:59.137774 | | 6 | 2017-12-31 08:46:13.239080 | | 7 | 2017-12-31 09:04:34.695830 | | 8 | 2017-12-31 12:27:05.253016 | | 9 | 2018-01-27 12:28:16.809840 | | 10 | 2018-02-14 07:27:18.847884 | | 11 | 2018-02-14 10:45:33.323448 Expected result should be 2 -
cURL doesn't show JSON data when using Django REST Framework
I'm having a problem with the tutorial for the Django REST framework 2. I'm using cURL to test the serializer I've built. I've also added some snippet data to the database. According to the tutorial, I should be able to do this: curl http://127.0.0.1:8000/snippets/ and see this: [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] I would also expect to see an HTTP response code of 200 where the Django server is running. If I simply enter the URI in my browser, I see the JSON data in my browser and the 200 response code in the Django server console. But when I run the curl command from the terminal command line, I don't see anything and I get a 301 HTTP response code in the Django console. What am I doing wrong (or not understanding) that is preventing me from seeing the JSON response in my terminal after I run the curl command? -
getting input from click event django/javascript
I have an html file that's a dataframe class. I added click event to each row using javascript after lots of reading online. What i am having trouble with, is using that click event as input into Django. Eventually, I want to be able to query a database that I am calling withing the views.py. As you can see, the sample html file contains rows of names. Hence, when the user clicks the row, i want to be able to use the first name, last name, state, address and zip as input within views.py. Sample code attached below: #sample HTML file <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>first</th> <th>LastName</th> <th>Address</th> <th>zip</th> <th>State</th> </tr> </thead> <tbody> <tr> <td>mary</td> <td>poppins</td> <td>3345 leanie rd</td> <td>28277</td> <td>PA</td> <tr> <td>honas</td> <td>bond</td> <td>1123 cavalry st</td> <td>38788</td> <td>GA</td> <script> function addRowHandlers() { var table = document.querySelector(".dataframe"); var rows = table.getElementsByTagName("tr"); for (i = 1; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); }; }; currentRow.onclick = createClickHandler(currentRow); } } window.onload = addRowHandlers(); </script> #views.py def query_result(request): fname = request.GET(//what do I type here?//) -
Django template get element in list of dictionary by index
I have the following: item = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}] In django template I would like to display the price of the first element: 15.52 I am already sending the size of item list so I am doing: {{i.item|index:forloop.counter0}} => This gets me {'itemCode': 'AZ001', 'price': 15.52} If I want price, what can I do? Doing {{i.item|index:forloop.counter0.price}} is giving me invalid key price at index 0. Any solution? -
Django ManyToManyField initializes with all objects by default
I have 2 classes, Player and Game. Players can own multiple games, so we are using a m2m relation inside the Player model: class Player(models.Model): games = models.ManyToManyField(Game) My problem is, when a new Player registers, for some reason they get all of the game objects that have been added to the database. How can I make it so the new player would initially have no games? -
Autocomplete with field related to ContentType
I need some help with an issue that I am not able to resolve on my own. So in this model, a tenancy document can either have a ForeignKey with building or property. I can't figure out how to add autocomplete fields to contenttype and in the dropdown, I just see building and property in admin form. I want to see building names and property names. I learned about autocomplete fields in Django 2.0, it's awesome but I don't know how can I use something like that in this particular case or if there is a better way to do this? Model: class TenancyDocument(models.Model): KINDS = Choices('Tenancy Agreement', 'Stamp Duty', 'Inventory List') id = FlaxId(primary_key=True) kind = StatusField(choices_name='KINDS') start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) content_type_limit = Q( app_label='properties', model='building') | Q( app_label='properties', model='property') content_type = models.ForeignKey( ContentType, limit_choices_to=content_type_limit, on_delete=models.CASCADE, verbose_name='Lease type' ) object_id = FlaxId(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.kind -
Django 1.11 - Create auth.user using class based views
I am building a custom admin that does CRUD operations on the models. While I was just using the default admin I didn't need to go into very advanced stuff. However, searching for info on what is the best approach on creating users, I found that it seems complicated to do this, especially using the class based views. The multiple inheritance makes it very difficult to sink into the codebase to understand outside-in what's going on. The main problems: The example on generic editing views is very basic and doesn't go into handling and validating passwords for example. Building the template requires using something like widget-tweaks to properly display the form fields, labels and the possible validation. What is the best practice here? I couldn't find how exactly should I handle the validation using the generic create Some complete example on a simple CRUD for the auth.user model would do a great amount of good to all of us Django newbies. Thanks -
How can i use prefetch_related in self related model
Hi i have Menu model which has ForeignKey named parent related with itself. If parent is None it means this menu is parent menu if it shows another Menu object it means it is submenu for its parent(many-to-one relation) Here is my problem i want to get all menus with its submenus using prefetch_related but i can not get it. How can i do it? Note: I do not want to get submenus going database each time in for menu Here is my model class; class Menu(models.Model): title = models.CharField(max_length=30) language = models.ForeignKey(Language) parent = models.ForeignKey("self", default=None, blank=True, null=True) href = models.CharField(max_length=255, default="#") menutype = models.CharField(max_length=50, default="gui") icon = models.CharField(max_length=100, default="chevron-right") order = models.IntegerField(default=0) target = models.CharField(max_length=50, default="_self") Here is my query; pm2 = Menu.objects.filter(parent=None, language__code=language, menutype=menutype).prefetch_related("submenus").order_by("order") for p in pm2: print(p.title) print(p.submenus) in here when i print the submenus the result is app.Menu.None -
In a Django ModelForm, how do I accept a datetime string that has milliseconds?
In a Django ModelForm's DateTimeField I want to have an input_format that accepts a datetime with milliseconds. e.g. '2018-02-26T14:46:15.704Z'. But strftime only has %f for microseconds. How do I add an input_format for to cope with this format? My field so far: class MyModelForm(forms.ModelForm): my_time = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%fZ',]) This will match: '2018-02-26T14:46:15.000704Z' but not: '2018-02-26T14:46:15.704Z' -
Modify nginx config to reverse proxy websockets properly
Current nginx config: server { listen 443 ssl http2; server_name NAME www.NAME; charset utf-8; ssl on; ssl_certificate /etc/nginx/ssl/NAME-cert.pem; ssl_certificate_key /etc/nginx/ssl/NAME-key.pem; location /static/ { alias /home/ubuntu/NAME/static_collection/; } location /media/ { alias /home/ubuntu/NAME/media_collection/; } location / { proxy_pass http://localhost:8002; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Everything works, apart from the websockets. I suppose this is because it doesn't deal with the http upgrade header... I've looked at the docs, but I can't figure out how to modify this config without breaking anything else. -
How to implement app marketplace in Django Rest framework?
I have a CRM product built on top of DRF and I want to provide my users an option to install add-ons to perform some additional tasks like sending bulk email using mailchimp etc. ; something like Slack app directory. Are there any built-in libraries available for this? If not, what is the best way to implement this? -
how do i link a field to a multi valued field in django model
This model Profile has different information about user and also a field called quiz which is a ManytoMany field. This field shows the quizes the user has registered for. I want the total_score field to store score user obtained in each quiz he participated. How do i do it? class Profile(models.Model): user=models.OneToOneField(User,related_name='Profile', on_delete=models.CASCADE) college=models.CharField(max_length=200) phone=models.IntegerField(blank=True,default=0) quiz=models.ManyToManyField(Quiz) total_score=models.IntegerField(default=0) def __str__(self): return self.user.username -
Generate input fields based on a input and store it properly
I have a field called subjects that asks users how many subjects do they have and based on the number they input I want to generate the input fields of same number. And How and where do I store those inputs. MODELS.PY #this field will determine how many input fields to generate subjects = models.IntegerField() VIEWS.PY def generate_forms(request): no_of_fields = request.GET.get('subjects') if no_of_fields: #generate other inupts #save it in the database Besides generating the input, how do I save those data in the database. Thanks in advance -
Need some guidance on running a finished project
Million Songs Dataset So, I was initially trying to run this project on my local machine, since the requirements are not specified in this project, I guessed what all tools were required. I can see that Django, MongoDB and Hadoop are required (additional tools maybe required). So I installed Django and generally Django projects have a "manage.py" file, which this project does not contain. I am also unable to determine which version of Django was used since this project was created over 4 years ago. So if anyone could point me in the direction which I am supposed to go, it would be very helpful. Thanks in advance. -
Setting form fields in django class based generic view CreateView
I'm using django's CreateView to add images to a book. I pass the book's id to the class based view as a parameter in the url. Form fields such as book and language are not rendered on the template, rather they're obtained with the help of the book's id. # views.py class PictureCreateView(CreateView): model = Upload fields = "__all__" book_id = None def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() self.book_id = self.kwargs['book_id'] book = Book.objects.get(id=self.book_id) initial['book'] = book initial['language'] = language initial['uploader'] = self.request.user return initial # set book_id so it used in the template def get_context_data(self, **kwargs): context = super(PictureCreateView, self).get_context_data(**kwargs) context['book_id'] = self.book_id return context def form_valid(self, form, **kwargs): print('Form is valid') self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return super(PictureCreateView, self).form_valid(form) def form_invalid(self, form): print('Form invalid!') print(form.errors) data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') # models.py class Upload(models.Model): image = models.ImageField(upload_to=get_upload_path, help_text='Image to process') uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader') language = models.ForeignKey(Language, models.CASCADE) book = models.ForeignKey(Book, models.CASCADE) The problem is that I get an error saying the form is invalid, and the fields uploader, book and language are required. How do I resolve this? -
Django model from multiple databes tables
I want to ask if there is a convenient way that allows me to create a django model from multiple tables. I am looking for solution, that can be written in similar way: class ClientTeamContacts(models.Model): attribute_1 = models.CharField(db_column='ss',db_table = 'xxx') attribute_2 = models.CharField(db_column='cc',db_table = 'yyy') I will be thankful for every suggestion that can provide some solution. -
Django: Joining on fields other than IDs (Using a date field in one model to pull data from a second model)
I'm attempting to use Django to build a simple website. I have a set of blog posts that have a date field attached to indicate the day they were published. I have a table that contains a list of dates and temperatures. On each post, I would like to display the temperature on the day it was published. The two models are as follows: class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField() date = models.DateField() class Temperature(models.Model): date = models.DateField() temperature = models.IntegerField() I would like to be able to reference the temperature field from the second table using the date field from the first. Is this possible? In SQL, this is a simple query. I would do the following: Select temperature from Temperature t join Post p on t.date = p.date I think I really have two questions: Is it possible to brute force this, even if it's not best practice? I've googled a lot and tried using raw sql and objects.extra, but can't get them to do what I want. I'm also wary of relying on them for the long haul. Since this seems to be a simple task, it seems likely that I'm overcomplicating it by having … -
Django ORM: Copying a translation field from one model to another issues an error
I have the following model: class AModel(TranslatableModel): ...... other fields definitions ...... translations = TranslatedFields( name=models.CharField(max_length=100, blank=False, default=''), description=models.CharField(max_length=500, blank=True, null=True) ) I have two instances of that model: "source" and "destination". When I try to copy translatable field from the source to the destination: destination.name = source.name An exception appears: NoTranslationError: Accessing a translated field requires that the instance has a translation loaded, or a valid translation in current language (en-us) loadable from the database Is there anyway to handle that? My configuration is: django-hvad==1.7.0 Django==1.8.8 -
How to create django queryset by reusing model instances and not performing additional DB query?
In my project I have the following setup. It has Project and EntryStatus models. Each project has it's own set of Statuses. When user creates a new Project, then I have to create default statuses for this project. Here is the code for my model manager. class EntryStatusManager(models.Manager): def create_default_for_project(self, project: Project): for status in self.get_queryset().filter(project=None): status.id = None status.project = project status.save() I want to return a queryset from this method that will contain all of the created statuses. The easiest solution is to make additional query like this def create_default_for_project(self, project: Project): created_ids = [] for status in self.get_queryset().filter(project=None): status.id = None status.project = project status.save() created_ids.append(status.id) return self.get_queryset().filter(id__in=created_ids) But is there any way to avoid making additional query and simply reuse created model instances? -
Not able to retrieve primary field : Django
I am trying to retrieve an integer field which is primary in the jquery success call back Below is my Model class PostEntry(models.Model): last_name = models.CharField(max_length=20) first_name = models.CharField(max_length=20) id = models.IntegerField(editable=False, primary_key=True) def __unicode__(self): return 'Entryid=' + str(self.id) + ',text="' + self.post_content + '"' JQuery success callback shows all field expect id field, AM I missing anything? -
Django: Removing unique constraint and creating migration
I have created a model and migrated in Django with a unique key constraint in one of the colom. Now am trying to remove the constraint and generate another migration file with the new change, but it says "Nothing seems to have changed". I tried with the command python manage.py schemamigration --auto -
How to store per-user data in django permanently and efficiently
I am working on a websie in django about books, where you can post reviews, rate the books etc... I'd like to know how to store data about every user in an efficient way, as to know whether the user: Has already posted a review for a specific book Has already rated a book This way, no user could post 2 reviews and I could provide a per-user experience. I even want to limit how many times they can rate (like 3 every month). Problems: Sessions do not seem useful since the data is not stored in the db and once the user exits and reenters the page, the session is gone (I checked the django docs but the example doesn't seem useful for me). I thought about adding dicts or lists in every instance of the model, and storing there all the necessary data, but I don't know whether it is appropriate/efficient Thank you very much for your time, I hope someone knows it! -
Unit Testing Django Model Save Function
I'm creating tests to check that a custom calibration model save function updates an asset record (foreign key) if it is the latest calibration record for the asset. The save function performs exactly as expected in live dev & production server and even in the django shell, but appears to fail during testing... models.py class Asset(models.Model): ... requires_calibration = models.BooleanField() passed_calibration = models.BooleanField(default=False) calibration_date_prev = models.DateField(null=True, blank=True) calibration_date_next = models.DateField(null=True, blank=True) class CalibrationRecord(models.Model): calibration_record_id = models.AutoField(primary_key=True) asset = models.ForeignKey( "myapp.Asset", on_delete=models.CASCADE, limit_choices_to={"requires_calibration": True} ) calibration_date = models.DateField(default=timezone.now) calibration_date_next = models.DateField(null=True, blank=True) calibration_outcome = models.CharField(max_length=10, default="Pass") def save(self, *args, **kwargs): super(CalibrationRecord, self).save(*args, **kwargs) # Check if this is the latest calibration record for any asset, if so update asset.calibration_dates and status latest_asset_calibration = CalibrationRecord.objects.filter(asset=self.asset.pk).order_by( "-calibration_date", "-calibration_record_id")[0] if self.pk == latest_asset_calibration.pk: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_prev=self.calibration_date) if self.calibration_date_next: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=self.calibration_date_next) else: Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=None) if self.calibration_outcome == "Pass": Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=True) else: Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=False) tests_models.py example failing test class CalibrationRecordTests(TestCase): def test_calibration_record_updates_asset_cal_date_prev(self): """ All calibration records should update related Asset record's "calibration_date_prev" to calibration_date """ asset1 = Asset.objects.create(asset_description="Test Asset 2", requires_calibration=True) self.assertIsNone(asset1.calibration_date_prev) cal = CalibrationRecord.objects.create(asset=asset1, calibration_description="Test Calibration 2", calibration_date=timezone.now()) self.assertEqual(cal.calibration_date, asset1.calibration_date_prev) Error log ====================================================================== FAIL: test_calibration_record_updates_asset_cal_date_prev (assetregister.tests_models.CalibrationRecordTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\[path]\app\tests_models.py", line 159, in test_calibration_record_u pdates_asset_cal_date_prev self.assertEqual(cal.calibration_date, asset1.calibration_date_prev) …