Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is loading fixtures from different app
Let's say my Django project has two apps, foo and bar and both the apps have fixtures in it with the same file name for fixtures for eg: user.json, client.json etc. When I am running the test for app foo like: ./manage.py test foo How come the fixtures from bar: bar/fixtures is being loaded for the test run only for foo? -
extract manytomany field from a queryset
Models.py class AllotmentDocket(models.Model): sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales') class MaterialRequest(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product = models.ManyToManyField(Product, related_name='kit_product') How can I get all the products information through the related AllotmentDocket? I tried : def PrintAllotmentDocket(request, pk): AlotmentDocket = get_object_or_404(AllotmentDocket, id=pk) kit = MaterialRequest.objects.filter(id=AlotmentDocket.sales_order).values('kit') but this gives an error: int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest' -
Rest uniform interface for calculator app
I am designing the rest api's for a basic calculator. I need to know which is the best practise for defining interfaces? /calc-service/add /calc-service/sub /cal-service/mul 2nd method /calc-service/?params -
Django: Query set to get AVG doesn't work
Currently, I try to get the average of all the answers to a specific question in my database. To achieve that I wrote the following query set. The answers are all numeric, but there still seems to be a problem with my query set. I receive the following error message function avg(text) does not exist LINE 1: SELECT AVG("surveys_answer"."answer") AS "avg" FROM "surveys... answers = Question.objects.filter( focus=QuestionFocus.AGE, survey__event=self.request.event, survey__template=settings.SURVEY_POST_EVENT, ).aggregate(avg=Avg('answers__answer')) models.py class Question(TimeStampedModel): survey = models.ForeignKey([...]) question_set = models.ForeignKey([...]) title = models.CharField([...]) help_text = models.TextField([...]) type = models.CharField([...]) focus = models.CharField([...]) required = models.BooleanField([...]) position = models.PositiveSmallIntegerField([...]) class Answer(TimeStampedModel): question = models.ForeignKey(related_name='answers') response = models.ForeignKey([...]) answer = models.TextField([...]) choices = models.ManyToManyField([...]) -
Django: Hiding the empty radio button option but still allowing it not to be null
I have a large model that I use over multiple pages. I made each page a separate form in my forms.py file. On some of the later form pages I include radio buttons. Based on what I've seen around Google, the only way to hide the empty radio button option is to make the radio button list required. In my case I did this the following way in my model: enlistment_date_known = models.CharField(max_length=10, choices=BOOL_CHOICES, blank=False, default=None) The problem is that these radio buttons are on my fourth page of my form, so when I submit the first page of my form, I get the following error: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert the value NULL into column 'enlistment_date_known', table 'LSPIntake_lonesoldier'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") Is there a way to allow the value of my radio buttons to be null in the database but still hide the first, blank option? Maybe by making the radio buttons required in the form instead of the model? -
I want to learn python Development. From where i can learn it easily? [on hold]
I want to learn python development with Django framework, From where i can learn it easily? I have some basic concepts of python -
Why list elements after space disappear when passed from views to Django template?
I use Django 2.1. I have some code in views.py: views.py ... zipped = zip(ph, mean) return render(request,'project/list.html', {'section': 'project', 'lines': zipped}) so far everything is correct, I debugged and all works. Data ph = ['Pre formation', 'Nice view'] #as an example not exact values mean = [10.0, 14.6] However inside html html {% for ph, mean in lines %} ... <td><input type="text" size="35" name="txt1" value={{ph}}></td> <td><input type="text" size="35" name="txt2" value={{mean}}></td> ... {% endfor %} Data I get Pre 10.0 Nice 14.6 Question: Why does it take only the text till space inside html? Inside views I debugged zipped has all information. How can I fix it? -
Decode JSON data before sending in API
I have created an API for a DB table. There is a field of 'day' which saves day in json formate like {"week1":["day1", "day2"], "week2":["day1", "day2"]} ({"1": ["3", "4"], "2": ["1", "2", "3"]}) Everything's working fine but I checked API on Postman, day is showing like this: "day": "{\"1\": [\"3\", \"4\"], \"2\": [\"1\", \"2\", \"3\"]}" when I checked Django admin, data is saving correctly in DB. Does any know how can I send decoded JSON data for this field? Here is my code: serializer.py class PlanToPackageSerializer(serializers.ModelSerializer): class Meta: model = PlanAllocationPackage fields = ('plan', 'day') depth = 1 class PackageListSerializer(serializers.ModelSerializer): package_name = PlanToPackageSerializer(many=True) class Meta: model = Package fields = '__all__' depth = 1 views.py class AllPackageView(APIView): def get(self, request): package = Package.objects.all() serializer = PackageListSerializer(package, many=True) return Response(serializer.data) -
Django localisation path separator Windows (\) vs macOS (/)
We've been maintaining a Django website with a few Mac and Linux users (through GitHub), but now a Windows-only person joined the team. We've come to one annoying little difference concerning the creation of .po localisation files. So far, we've always had paths with forward slashes: #: core/templates/home.html:8, but the Windows user generates paths with backslashes: #: .\core\templates\home.html:8. This makes it much more difficult to spot changes, since 750+ lines change everytime, rather than only the new or changed text & translations. I tried myself on a Windows computer and have the same result. What can we do to unify this? Thanks! -
Get data from JsonResponse in django
I wanted to know how to get data from a JsonResponse in django. I made a JsonResponse that works like this def pfmdetail(rsid): snpid = parseSet(rsid) if not snpid: return HttpResponse(status=404) try: data = SnpsPfm.objects.values('start', 'strand', 'type', 'scoreref', 'scorealt', rsid=F('snpid__rsid'), pfm_name=F('pfmid__name')).filter(snpid=snpid[0]) except SnpsPfm.DoesNotExist: return HttpResponse(status=404) serializer = SnpsPfmSerializer(data, many=True) return JsonResponse(serializer.data, safe=False) and then I call directly the method like this def pfmTable(qset,detail): source = pfmdetail(detail) print(source) df = pd.read_json(source) but it gives me an error. I know it's wrong because with the print it returns the status of the response which is 200 so I suppose that the response is fine but how can I access the data inside the response? I tried import json to do json.load but with no success. I even tried the methods of QueryDict but stil I can't acess to the content I'm interested P.S. I know that data contains something because if i display the jsonresponse on the browser i can see the JSON -
How to check if submit name is there or not in self.client.post?
Here I am writing test for function delete_position but I got little problem here.I am getting AssertionError: 302 != 200 which is I think because I have not send delete_single name in client.post but it is defined in my views. How can I check if delete_single is in request.POST in my test_delete_position ? views.py def delete_position(request, pk): position = get_object_or_404(Position, pk=pk) if request.method == 'POST' and 'delete_single' in request.POST: position.delete() messages.success(request, '{} deleted.'.format(position.title)) return redirect('organization:view_positions') else: messages.error(request, 'Sorry.Invalid request.') tests.py class PositionTestCase(TestCase): def setUp(self): # create admin user for authentication self.admin = get_user_model().objects.create_superuser(username='admin', password='password@123',email='admin@admin.com') self.client = Client() self.position = Position.objects.create(title='Sr.Python Developer') def test_delete_position(self): self.client.login(username='admin', password='password@123') response = self.client.post(reverse('organization:delete_position', kwargs={'pk': self.position.pk})) print(response) self.assertEqual(response.status_code, 200) -
How to pass the data through button using unique id in a dynamic table
i am using django and bootstrap and i want to pass data through button and show that data on bootstrap popup modal and i want that in each loop x.bots data should be passed uniquely so that i can access bot title ,bot id using another loop at x.bots {% for x in data %} <td>{% if x.bots %}<a href="#myModal" class="btn btn-primary btn-sm" data-toggle="modal" data="x.bots"> Show Bots &nbsp;{{ x.bots|length }}{% endif %}</a></td> {% endfor %} this is my script file <script> $(document).on('show.bs.modal','#myModal', function (event) { var button = $(event.relatedTarget); var recipient = button.data(x.bots); var modal = $(this); modal.find('.modal-title').text('Bots Title'); modal.find('.modal-body input').val(i); }) </script> but i tried alot using different ways but not getting the data -
How to show all total values in top not on every data
Here i am trying to get total values of all field and i got result but i want to show only one time all values not in every data so how to show this data in top only once "count": 6, "next": null, "previous": null, "results": [ { "pk": 1, "user": "Rahul Raj", "trwalk": 32, "Dtwalk": 13, "trclassic": 45, "Dtclassic": 16, "trelectric": 32, "Dtelectric": 12, "totalMilage": 122, "totalweight": 212, "phone": "372377233", "total_milage": 732, "total_weight": 1272, "total_travel_walk": 192, "total_distribute_walk": 78, "total_travel_classic": 270, "total_distribute_classic": 96, "total_travel_electric": 192, "total_distribute_electric": 72 }, But i want result like this "count": 6, "next": null, "previous": null, "total_milage": 732, "total_weight": 1272, "total_travel_walk": 192, "total_distribute_walk": 78, "total_travel_classic": 270, "total_distribute_classic": 96, "total_travel_electric": 192, "total_distribute_electric": 72 "results": [ { "pk": 1, "user": "Rahul Raj", "trwalk": 32, "Dtwalk": 13, "trclassic": 45, "Dtclassic": 16, "trelectric": 32, "Dtelectric": 12, "totalMilage": 122, "totalweight": 212, "phone": "372377233", }, and here is my code of serializers.py class UlectricSerializer(serializers.ModelSerializer): total_milage = serializers.SerializerMethodField() total_weight = serializers.SerializerMethodField() total_travel_walk = serializers.SerializerMethodField() total_distribute_walk = serializers.SerializerMethodField() total_travel_classic = serializers.SerializerMethodField() total_distribute_classic = serializers.SerializerMethodField() total_travel_electric = serializers.SerializerMethodField() total_distribute_electric= serializers.SerializerMethodField() class Meta: model = Muser fields = ('pk','user','trwalk','Dtwalk','trclassic','Dtclassic','trelectric','Dtelectric','totalMilage', 'totalweight','phone','total_milage','total_weight','total_travel_walk','total_distribute_walk', 'total_travel_classic','total_distribute_classic','total_travel_electric','total_distribute_electric') # Total Milage and Weight by Electric def get_total_milage(self, obj): totalpieces = Muser.objects.all().aggregate(total_milage=Sum('totalMilage')) return totalpieces["total_milage"] … -
Generating a Django Model that can have multiple values in one field
I am trying to generate a Django model that can handle multiple values in a single field. As such, when the first field is queried through a view, a user should select a value for the second view through a select box. To give a background of the problem, my seeding fixture looks like this... In the above scenario, location is the intended name of my model. Now, through a form, I want a user to be presented with 'countynames'. Upon selecting a countyname, the user should be presented with 'placenames' in the selected county for them to choose. I have tried the following format for the model... Now, I know that the error that is thrown, ('places' is not defined), is warranted. I was asking whether there is a way to define it (places), as it is in the fixture, or if anyone has a better implementation for such a model... any alternative way is welcome and appreciated as I can't think of anything at this point. -
How to use 'inspectdb_refactor' tool in django python?
I am trying to create models using postgresql, but it is giving me an error. I was using the following command. python manage.py inspectdb_refactor --database=garo2py --app=products I also added the inspectdb_refactor to my INSTALLED_APPS inside settings.py and also gave a database credentials as per following. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'garo2py', 'USER': 'projop', 'HOST':'localhost', 'PORT': '5432', } } I got the following error. Traceback (most recent call last): File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 166, in ensure_defaults conn = self.databases[alias] KeyError: 'garo2py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\inspectdb_refactor\management\commands\inspectdb_refactor.py", line 118, in handle self.handle_inspection(options) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\inspectdb_refactor\management\commands\inspectdb_refactor.py", line 123, in handle_inspection connection = connections[options['database']] File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 198, in __getitem__ self.ensure_defaults(alias) File "C:\Users\DipakGiri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 168, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection garo2py doesn't exist -
Django-filter ForeignKey related Model filtering
I've been struggling with dajngo-filter recently. I have 2 models: Book and Author. class Book(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(Author, on_delete=model.CASCADE) length = models.PositiveIntegerField() class Author(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) year_of_birth = models.DateFiled() So, I'd like to make filter page, where you can find book by it's properties (title, author etc) AND information about author. For example book shorter than 300 pages, which author is beetween 20-25 years old. In filters.py I have: import django_filters from .models import Book, Author class BookFilter(django_filters.FilterSet): class Meta(): model = Book fields = ['title', 'author'] And have actually no idea how to also filter by different model, which is related by ForeignKey to Book model. I have really little experience with Dajngo, I wonder if it's very complex problem or not. :) Thanks! -
How to render StructBlock which is inside StreamBlock to template?
How can I render heading, text, image in my carousel_block.html template. I can't access these. Here is my code. My custom block class CarouselBlock(blocks.StreamBlock): carousel_items = blocks.StructBlock([ ('heading', blocks.CharBlock(label='Nadpis', max_length=128)), ('text', blocks.CharBlock(label='Text')), ('image', ImageChooserBlock(label='Obrázek')), ]) class Meta: template = 'cms/blocks/carousel_block.html' This is my html template, where I want to render heading, text and image <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for carousel_items in self.carousel_items %} {% image carousel_items.value.image max-1920x1080 as image_1920 %} <div class="carousel-item {% if forloop.first %}active{% endif %} "> <section class="banner-area" id="home" style="background-image: url({{ image_1920.url }})"> <div class="container"> <div class="row justify-content-start align-items-center"> <div class="col-lg-6 col-md-12 banner-left"> <h1 class="text-white"> {{ carousel_items.value.heading }} </h1> <p class="mx-auto text-white mt-20 mb-40"> {{ carousel_items.value.text }} </p> </div> </div> </div> </section> </div> {% endfor %} <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> -
How to start a background thread on django to run everytime is launched and if some conditions are fullfilled?
I'm facing this situation: I have an app backend on Django that process the data of the app. In certain cases the users are allowed to join a waitlist for doing certain tasks. If the user is going to do a task and there's nobody in the waitlist, it is allowed to do it (it is joined into the waitlist with the status of "doing the task" and redirected in the app to the action screen. But if the user is going to to a task and there are someone in the waitlist it is joined with the status of "waiting". When his turn comes, the backend sends a notification trough Firebase Cloud Messaging for him to do the task and set him in the waitlist as "doing the task". The main problem is that users has time limits to accept his turn in the waitlist, so everytime a user is notified i have to wait for 60 seconds. If that time is over the user is deleted form the waitlist and the next is notified. How can I accomplish this on Django so the users can interact with the app, making petitions through the API and having that running … -
How to make user email unique in Django?
Hi I'm just trying to create a signUp form in Django but not able to make email field unique. Please tell me how to make that email field unique so any other user can't signUp using the same email. class User(models.Model): user_name = models.CharField(max_length=50,unique=True) first_name = models.CharField(max_length=50,blank=False) last_name = models.CharField(max_length=50,blank=False) User_email = models.EmailField(max_length=70,blank=False,unique=True) password = models.CharField(max_length=12,blank=False) -
How to Fast Search with Django Which Supports JSONField?
I'm looking for a fast searching alternative for my postgres jsonfield,I'm storing a large JSON dataset in below web_results JsonField , Using default objects filtering over that field takes a lot of time. I'm looking for any fast alternative to query the results. models.py class Web_Technology(models.Model): web_results = JSONField(blank=True,null=True,default=dict) ### Large dataset web_results field format as follow: {"http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}} I tried using django elasticsearch dsl for mapping the above field with elasticsearch but that doesn't seem to support jsonfield as described in below thread. https://stackoverflow.com/questions/57866149/jsonfield-workaround-on-elasticsearch-mapperparsingexception If you have any suggestion/alternative/libraries which support above jsonfield for making fast searches across all json objects, Do let me know. -
How do I filter my model within itself twice in Django?
I'm looking for some help with filtering my model twice in Django. This is my current model: class Medarbejder(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) ma = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") fornavn = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") efternavn = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") holdnavn = models.CharField(max_length=200, null=False, help_text="Indtast medarbejderens hold.") delingnavn = models.ForeignKey('Deling', on_delete=models.CASCADE, null=True) fagnavn = models.ForeignKey('Fag', on_delete=models.CASCADE, null=True) The model is a model for employees (medarbejder). Now I wish to filter the teamname (holdnavn) with distinct, which I have accomplished. The next step is to then filter all the departments (delingnavn) within each teamname (holdnavn). So when I click on one teamname such as "GSU19", then I wish to get a list of all the departments within that teamname only. I can't seem to wrap my head around how to do this? I am able to do it with slug and with pk, but both teamname and department are not a slug or a pk, so I'm abit lost to how to get the value in the url and filter again. This is currently how the URL looks after I click on a specific teamname: http://127.0.0.1:8000/hold/%3CQuerySet%20%5B%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%204%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%205%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%206%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%202%7D,%20%7B'delingnavn_id':%203%7D,%20%7B'delingnavn_id':%203%7D%5D%3E/ I'm getting all the department id's in the url..which is not … -
Form not registering on Django Admin
I have two forms on the profile page and when I submit them, it successfully submits the form but is not registering on the admin. What should I do? I've been building this app for over a month already but is stuck at 70%. My models are: class Translate(models.Model): title = models.CharField(max_length=255) body = models.CharField(max_length=10000) class Meta: verbose_name = "translation" verbose_name_plural = "translations" def __str__(self): return self.title class Narrate(models.Model): title = models.CharField(max_length=255) body = models.CharField(max_length=10000) class Meta: verbose_name = "narration" verbose_name_plural = "narrations" def __str__(self): return self.title Now on my views.py, it's structured this way because it has 2 forms on one page. Is it better to used class based views on my situation or function based views? class ProfilePageView(TemplateView): template_name = 'profile.html' def get(self, request, *args, **kwargs): add_narration = NarrateForm(self.request.GET or None) add_translation = TranslateForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['add_narration'] = add_narration context['add_translation'] = add_translation return self.render_to_response(context) class NarrateFormView(FormView): form_class = NarrateForm template_name = 'profile.html' def post(self, request, *args, **kwargs): add_narration = self.form_class(request.POST) add_translation = TranslateForm() if add_narration.is_valid(): add_narration.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( add_narration=add_narration, ) ) def submittedView(request): return render(request, 'submission.html') class TranslateFormView(FormView): form_class = TranslateForm template_name = 'profile.html' def post(self, request, … -
How to make html call a javascript function from an external js file, in Django environment
I am developing an app with Django. I want an alert windows pops up as soon as the user lands on a certain HTML page. The javascript function that makes the window pop up is called funprova and this function is stored inside a js file called prova.js, at the path static/js/prova.js I want HTML call this function. How do I do that? -
I am new and just installed Python3.7.4 on Windows 10 and tried to check pip -v in cmd but got this error. OSError: [Errno 9] Bad file descriptor[1]
I am using windows 10 and just installed python3.7.4 but when I run pip -v in cmd, it gives me an error OSError: [Errno 9] Bad file descriptor[1]. I also installed conda and run anaconda-navgator but got the exact same error. I am stuck -
(django) define models dynamically for importing different columns of csv files
I want to make web Test Report system using django to display hundreds type of csv files. each csv files have different fields and i have to display all of these csv files . so i want to define new models dynamically when new csv files(test result data)was made and has to be imported to model is there any way to solve this?