Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to range items in for loop?
I am fetching data from database by the name field.title and field.img in views.py and I made loop and gave range to it of 2 items but it is fetching every item from database. I use __ in for loop range but whenever I use field in range it gives me AttributeError. Destination is a class in models.py target1 = Destination.objects.all() for field in target1: for __ in range(2): field.img field.title -
Django Unable to import models
Actually am trying to import a models form posts folder and i am getting this following error.. AttributeError: module 'posts' has no attribute 'views' here is urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls import include import accounts import posts urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name = 'home'), path('login/',include('accounts.urls')), path('signup/',accounts.views.signup, name='signup' ), path('logout/',accounts.views.logout, name='logout'), path('posts/',posts.views.myposts) ] here is my posts folder Here is my posts.views from django.shortcuts import render, HttpResponse # Create your views here. def myposts(request): return HttpResponse('all_post.html') -
Django Can't Resolve Style ine fil static
Hello i can't resolve static file (vendor,bootstrap,css,js) i can t see the picture with color just baisc formular need help to resolve this i followed the documentation step by step but this step didnt work this is my code html : <!DOCTYPE html> <html lang="en"> <head> {% load static %} <title>Login V9</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--===============================================================================================--> <link rel="icon" type="image/png" href="{{ static 'AppStage/images/icons/favicon.ico' }}"/> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/bootstrap/css/bootstrap.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/fonts/font-awesome-4.7.0/css/font-awesome.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/fonts/iconic/css/material-design-iconic-font.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/animate/animate.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/css-hamburgers/hamburgers.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/animsition/css/animsition.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/select2/select2.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/daterangepicker/daterangepicker.css' %} "> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/css/util.css' %} "> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/css/main.css' %} "> <!--===============================================================================================--> </head> <body> <div class="container-login100" style="background-image: url('images/paul.jpg');"> <div class="wrap-login100 p-l-55 p-r-55 p-t-80 p-b-30"> <form class="login100-form validate-form"> <span class="login100-form-title p-b-37"> Sign In </span> <div class="wrap-input100 validate-input m-b-20" data-validate="Enter username or email"> <input class="input100" type="text" name="username" placeholder="matricule"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-25" data-validate = "Enter password"> <input class="input100" type="password" name="pass" placeholder="password"> <span … -
Filtering by variable's value. How does .filter(**{filter_name: filter_value}) work?
So this magic: filter_name = 'some_field_from_model' filter_value = 'some_val' Object.filter(**{filter_name: filter_value}) works. But how does it work? What does ** do? I am fascinated but I don't understand this at all. Can someone explain what is happening here? Thanks a lot. Python newb here. -
How can I add manual ordering to multiple different models in django?
In django I am trying to build a menu app that will allow users to build and edit a restaurant menu, then display it to users. A menu has Sections, subsections, and menu items that the user should be able to put in any order that they want, and have that order displayed to the user. For example, a menu might look like: Appetizers Calamari Soup Entrees Sandwiches Hamburger Cuban Steaks Ribeye Here are the models that I am using for this: class Section(models.Model): title = models.CharField(max_length=50) parent_section = models.ForeignKey( 'Section', on_delete=models.CASCADE, blank=True, null=True ) menu = models.ForeignKey( 'Menu', on_delete=models.CASCADE ) def __str__(self): return self.title class MenuItem(models.Model): name = models.CharField(max_length=50) description = models.TextField() menu = models.ForeignKey( 'Menu', on_delete=models.CASCADE ) section = models.ForeignKey( 'Section', on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return self.name I am confused about the best way to solve this problem. I have thought about adding an order_number property to all both the Section and MenuItem models, however, I feel like this would create a nightmare for editing objects when an item or section is dragged from one part of the menu to another, as well as requiring much more backend code when putting together the whole menu in … -
How to correctly deserialize datetime objects stored in JSONField with DjangoJSONEncoder?
I'm storing datetime objects in a JSONField with Django 2.1 and a PostgreSQL, but I can't find a way to correctly deserialize them when querying database : I've tried to use DjangoJSONEncoder which works correctly for serialization. But deserialization does'nt work properly class Book(models.Model): data = JSONField(encoder=DjangoJSONEncoder) class BookTest(TestCase): def test_JSONField_deserialize(self): # record it in PostgreSQL Database : instance = Book.objects.create(data= {'date': tz.now()} ) # Retrieve it from PostgreSQL Database : result = Book.objects.get(id=instance.id) # Test the type : self.assertEqual(type(result.data['date']), datetime) AssertionError: <class 'str'> != <class 'datetime.datetime'> What am I doing wrong ? Do I need to extends DjangoJSONEncoder, or provide a .from_db_value() custom method ? -
How to add data to an existing JSONField like a Set
I wanna add for example "id" to an existing JSONField on my postgres database in django using django ORM I've tried: User.objects.filter(id=user_id).update(followings=[follow_user_id]) but with this I can just add one value to JSONField and just change it in the future As you can see I don't need [key: "value"] I just need something like this: ["value1", "value2", "value3", ...] Many Thanks -
Django: Accessing extra field in ManytoMany (through=)
I am trying to access the purchaser field in my ManytoMany field. I used through= to add some extra fields. However, it seems I am only able to access the event object, not the extra fields. Can someone explain to me why? for selected_order in Order.objects.all(): contact_exists = Contact.objects.filter( email=selected_order.email, event_related_fields=selected_order.event, ) if contact_exists: contact = contact_exists.first() for x in contact.event_related_fields.all(): print(x.purchaser) models.py class Contact(TimeStampedModel): consent = models.BooleanField(verbose_name=_("Consent")) email = models.EmailField(verbose_name=_("Your email")) first_name = models.CharField( max_length=100, # TODO Length must be same as for billing model verbose_name=_("First name"), null=True, blank=True, ) last_name = models.CharField( max_length=100, # TODO Length must be same as for billing model verbose_name=_("Last name"), null=True, blank=True, ) events = models.ManyToManyField(Event, related_name='contacts') event_related_fields = models.ManyToManyField( Event, related_name='event_related_fields', through='EventRelatedFields' ) organizer = models.ForeignKey( Organizer, on_delete=models.PROTECT, related_name='contacts' ) # PROTECT = don't allow to delete the organizer if contact exists class Meta: verbose_name = _("Contact") verbose_name_plural = _("Contacts") ordering = ('created',) unique_together = ('email', 'organizer') def __repr__(self): return "{}: {}".format(self.__class__.__name__, self) def __str__(self): return self.email class EventRelatedFields(TimeStampedModel): event = models.ForeignKey(Event, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) lead = models.BooleanField( verbose_name='Lead', default=False ) # Contact who 'Signed Up' attendee = models.BooleanField( verbose_name='Attendee', default=False ) # Contact assigned to ticket purchaser = models.BooleanField( … -
Django forms - How i make a ModelChoiceField to show data only if another select value is selected
I have a select witch contains over 50.000 options. When I access the page I need to wait 3 s to load that page because of that... I must to find a solution to use another select to filter that select or to not load all data when i access the page. Can anyone give me some advice? -
500 Internal Server Error django + mod_wsgi + apache2 on ubuntu 16
I am trying to deploy my application on Ubuntu server i have done everything correct as far as i know but i am always getting the 500 internal server issue error. I have tried so many troubleshooting guides but i cannot find anything useful that ca resolve the issue. Here is the /etc/apache2/sites-available conf file Alias /static /home/local/user/wesupportapp/static <Directory /home/local/user/wesupportapp/static> Require all granted </Directory> Alias /media /home/local/user/wesupportapp/media <Directory /home/local/user/wesupportapp/media> Require all granted </Directory> <Directory /home/local/user/wesupportapp/wesupportapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/local/user/wesupportapp/wesupportapp/wsgi.py WSGIDaemonProcess django_app python-path=/home/local/user/wesupportapp python-home=/home/local/user/wesupportapp/venv WSGIProcessGroup django_app When i run the application on the developement server of django everything works well but once i enable the app conf file i have the 500 error. If someone had then same issue pi am facing that can really help me resolving this it will be so much appreciated. -
Django query not passing to AJAX in JSON Format
I'm trying to simply fill a textfield with its corresponding database value using Django and AJAX. The goal is that when the dropdown value is changed the textfield auto-updates. I get the following error in console: SyntaxError: Unexpected token < in JSON at position 3 & Uncaught ReferenceError: data is not defined I have tried doing it without the JSON but then the data turns out to be the whole html code of the currently loaded page. tasks.html <form method="POST" id="function" function-url="{% url 'synctool:load_function' %}" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit">Execute</button> </form> <script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script> $("#id_function_name").change( function () { var url = $("#function").attr("function-url"); var function_id = $(this).val(); console.log(function_id) $.ajax( { url: url, dataType: "json", data: { 'function_name': function_id }, success: function (data) { console.log('success') $("#id_script_location").val(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log('jqXHR:'); console.log(jqXHR); console.log('textStatus:'); console.log(textStatus); console.log('errorThrown:'); console.log(errorThrown); } }); console.log("ajax executed") }); </script> urls.py url(r'^$', views.load_script, name='load_function'), views.py def load_script(request): function_id = request.GET.get('function_name') query = serialize('json', Task.objects.filter(function_name_id = function_id).values(), cls=LazyEncoder) return query -
Why when I open Terminal(On pycahrm) shows (base) not (venv)?
I'm setting up my server.In web application. I'm on Windows. I have tried so many methods, when I write " python manage.py runserver" ," python: can't open file 'manage.py': [Errno 2] No such file o r directory " . def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BlediShop.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() " python: can't open file 'manage.py': [Errno 2] No such file or directory " -
Appending delta column with an existing DataFrame
I have a dataframe which calculates the delta score(currentdate - timedelta) for a ticker that looks like the following: TICKER_id DXJ EWA EWC EWG EWI EWP EWQ EWU EWW EWY EWZ DATE 2019-05-20 -1.0 1.5 0.0 -0.5 0.0 0.0 0.5 0.0 -0.5 0.0 0.0 2019-05-21 -1.0 1.5 0.5 -0.5 0.0 0.0 0.0 0.0 -0.5 -0.5 0.0 2019-05-22 -1.0 1.5 0.0 -1.0 0.0 0.0 0.0 0.0 -0.5 -0.5 0.0 I am trying to append these scores to the already existing queryset, in between 'TICKER_ID' and 'FINAL_SCORE' which looks like this for example: [{'id': 00001, 'DATE': datetime.date(2019, 7, 8), 'TICKER_id': 'DXJ', 'FINAL_SCORE': -0.5, 'MODEL_SCORE': -0.5, 'G': 0.0, 'L': 0.0, 'R': 0.0, 'RV': -1.0, 'SN': -1.0, 'TC': -1.0, 'FN': 0.0} This is the code for calculating the delta scores: lag_scores_df = pd.DataFrame([x for x in overall_scores.objects.filter(TICKER__in = countries, DATE__gte = lag_date).values()]) lag_scores_df = lag_scores_df.pivot_table(index = 'DATE', columns = 'TICKER_id', values = 'FINAL_SCORE') lag_scores_df.fillna(method= 'ffill', inplace = True) lag_scores_df.diff(21) My thought is to create a dictionary to hold the delta scores and increment from the overall_scores.objects Any help would be greatly appreciated! -
Get the last occurance of a Queyset
I have the following Queryset qs = Model.objects.\ filter(user_id=request.user.pk).\ only('item_id', 'action', 'performed_at').\ order_by().\ order_by('performed_at') This Queryset will fetch some duplicate Models but with different performed_at and with same item_id. What I want is to keep most recent occurance by item_id keeping the order_by and without evaluating the Queryset. -
Django: Filter many to many field
I expect to receive a var contact_exists that I can use to update some fields. However, the following query always gives me back django.core.exceptions.FieldError: Related Field got invalid lookup: event Do you have any idea why event_related_fields__event doesn't work the way I expected? for selected_order in Order.objects.all(): contact_exists = Contact.objects.filter( event_related_fields__event=selected_order.event, ) Here my models.py: class Contact(TimeStampedModel): consent = models.BooleanField(verbose_name=_("Consent")) email = models.EmailField(verbose_name=_("Your email")) first_name = models.CharField( max_length=100, # TODO Length must be same as for billing model verbose_name=_("First name"), null=True, blank=True, ) last_name = models.CharField( max_length=100, # TODO Length must be same as for billing model verbose_name=_("Last name"), null=True, blank=True, ) events = models.ManyToManyField(Event, related_name='contacts') event_related_fields = models.ManyToManyField( Event, related_name='event_related_fields', through='EventRelatedFields' ) organizer = models.ForeignKey( Organizer, on_delete=models.PROTECT, related_name='contacts' ) # PROTECT = don't allow to delete the organizer if contact exists class Meta: verbose_name = _("Contact") verbose_name_plural = _("Contacts") ordering = ('created',) unique_together = ('email', 'organizer') def __repr__(self): return "{}: {}".format(self.__class__.__name__, self) def __str__(self): return self.email class EventRelatedFields(TimeStampedModel): event = models.ForeignKey(Event, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) lead = models.BooleanField( verbose_name='Lead', default=False ) # Contact who 'Signed Up' attendee = models.BooleanField( verbose_name='Attendee', default=False ) # Contact assigned to ticket purchaser = models.BooleanField( verbose_name='Purchaser', default=False ) # Contact made the order … -
How to replace LocaleRegexURLResolver (removed in later versions of djangorestframework)
I am currently working on a Django version bump from 1.11 to 2.2. In the process I had to bump the version of djangorestframework as well (to 3.9.4), which removed LocaleRegexURLResolver class completely from it's latest versions. Is there any class which works as a substitute for this class? I wasn't able to find any substitute for this class neither any solution for this problem. class SiteLocaleRegexURLResolver(LocaleRegexURLResolver): """ Overrides LocaleRegexURLResolver to use specified default language by site instead of global default language """ def __init__( self, urlconf_name, site, default_kwargs=None, app_name=None, namespace=None, prefix_default_language=True ): super(LocaleRegexURLResolver, self).__init__( None, urlconf_name, default_kwargs, app_name, namespace, ) self.prefix_default_language = prefix_default_language self.default_language = site.language_code @property def regex(self): language_code = get_language() or self.default_language if language_code not in self._regex_dict: if language_code == self.default_language and not self.prefix_default_language: regex_string = '' else: regex_string = '^%s/' % language_code self._regex_dict[language_code] = re.compile(regex_string, re.UNICODE) return self._regex_dict[language_code] Basically it changes the default language. In UK, site /docs/ would be in english and /fr/docs/ in french. In FR on the other hand, /docs/ would be in french and /uk/docs/ in english -
is it possible to have a normal form and a dynamic field form separate for a single model
i am trying to avoid using Foreign Keys and i want to have a single model with three fields as following: company_name team_member position company_name field is normal form while the other fields in a dynamic form where more team members are addedd. any advise on how to approach it and is it possible. i tried having them in separate models with foreign key relation but failed to get the foreign key assigned automatically to get the company name. -
I restarted docker but now nginx won't connect. What can i do?
I restarted docker with the command: sudo systemctl restart docker Now, my nginx won't connect. I haven't changed any of the nginx config files and have tried sudo service nginx restart but nothing -
How to fix " 'ErrorDict' object has no attribute 'status_code' " in django form validation
I am trying to validate my form but ending with error, I am trying to get two models in one form. views.py: def ipd (request,patient_id): patient = Patient.objects.get(pk=patient_id) if request.method=="POST": data = dict(request.POST) data['patient']=Patient.Patient_id formtwo = IpdForm(request.POST) if formtwo.is_valid(): if formtwo.save(): return render('ipd_list', messages.success(request, 'Patient is successfully updated.', 'alert-success')) else: return render('ipd_list', messages.error(request, 'Data is not saved', 'alert-danger')) else: return formtwo.errors else: formtwo = IpdForm() return render(request, 'newipd.html', {'form2':formtwo ,'form':patient}) -
Update external lib patch used for test Django command
I'm testing a Django command which uses an external API named redminelib. My mock class and patch in tests work pretty well but when I tried to patch command twice on same test with two different Mock instances, second command call use the first mock class instance. Django command in my_project/app/management/commands/redmine_command.py: from redminelib import Redmine class Command(BaseCommand): def handle(self, **options): key = 'project' redmine_api_instance = Redmine({'user': 'pass'}) redmine_project = redmine_api_instance.project.get(key) print(redmine_project) In my_project/app/tests.py: import unittest import json from django.core.management import call_command from django.test import TestCase class MockProject: """A project mock class""" def __init__(self, time_entries: list): self.time_entries = time_entries class MockRedmine(unittest.mock.MagicMock): """Class who will mock the redminelib API""" # Define directory which contains data files json_data_dir = os.path.join(settings.BASE_DIR, "app/testdata/") def __init__(self, json_project_file, *args, **kwargs): super().__init__(json_project_file, *args, **kwargs) self.project = self.load(json_project_file) def load(self, json_file): json_filepath = os.path.join(MockRedmine.json_data_dir, json_file) with open(json_filepath, "r") as f: json_dict = json.load(f) project_dict = {key: MockProject(values) for key, values in json_dict.items()} return project_dict # I test some case like this it works: class TestCommand(TestCase): def test_invoice_creation_amount_and_update(self): with unittest.mock.patch("redminelib.Redmine") as redmine_mock_inst: mock_redmine = MockRedmine("api_case.json") redmine_mock_inst.return_value = mock_redmine call_command("my_command") Now I use two differents data set: api_case.json and other_api_case.json: class TestCommadTwice(TestCase): def test_invoice_creation_amount_and_update(self): with unittest.mock.patch("redminelib.Redmine") as redmine_mock_inst1: mock_redmine1 = MockRedmine("api_case.json") … -
How can I search the choice field using display name?
I want to query the item from the database using django SmallIntegerField. The code I used is Here is the class defination: class Equipment(models.Model): asset_status = ( (0, 'online'), (1, 'offline'), (2, 'unknown'), (3, 'wrong'), (4, 'x'), ) status = models.SmallIntegerField( choices=asset_status, default=0, verbose_name='Device Status') The query code I used is def filter_queryset(self, qs): sSearch = self.request.GET.get('search[value]', None) print(sSearch) if sSearch: qs = qs.filter(Q(status__icontains=sSearch)) return qs I want to query this column by 'online', 'offline' and so on. Do you know how to do this? The reference I have searched are Search choice field by the name in django - python I also see the Choices API in https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices But there is no Q. I am not sure whether it works. Could you please tell me about this? Thanks -
JQuery pop-up ONLY when Django form is valid
This is a Django form in HTML. The JQuery creates a pop-up message when form is submitted ("New card added"). However, the message is displayed even if the form is not valid. I have tried using if($("#new_card_form").valid()) but it outputs an TypeError: $(...).valid is not a function HTML Script <script type="text/javascript"> $( document ).ready(function() { $("#pop_up").click(function(event) { if($("#new_card_form").valid()) alert("New card added"); }); }); </script> HTML Form <form action="/new/" method="POST" class="form-group" id="new_card_form"> {% csrf_token %} <div class="form-control form-control-lg"> <strong>Full name:</strong> {% render_field form.cardholders_name type="input" %} </div> <div class="form-control form-control-lg"> <strong>Card number:</strong> {% render_field form.card_number type="input" %} </div> <div class="form-control form-control-lg"> <strong>Amount (in €):</strong> {% render_field form.card_balance type="input" %} </div> <!-- Input type submit bind jquery pop up message --> <input id="pop_up" type="submit" value="Submit" class="form-control btn btn-primary"> </form> I have a hunch there is a simple solution. I would really appreciate your input. -
Performance of django API view pagination
I am new to python django. I am using APIView. I am looking at pagination code. I have looked through many codes but in all those, i have a concern. They all get all the data from the table and then paginate that data. zones = Zone.objects.all() paginator = Paginator(zones, 2) page = 2 zones = paginator.page(page) serializer = ZoneSerializer(zones, many=True) return {"data": serializer.data, 'count': zones.paginator.count, "code": status.HTTP_200_OK, "message": 'OK'} My expectation is that i don't get all the records and then paginate using paginator. Otherwise i will have to write my own code to handle it. -
client login activity tracking in django
i have login code but i want when i was logged in and logged out my recuirment is to track the clients from django.shortcuts import render from django.http import HttpResponse from django.core.signals import request_finished from django.dispatch import receiver,Signal from datetime import datetime from .models import ,LoginLogoutLog from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed def home(request): request_counter_signal.send(sender=LoginLogoutLog) return HttpResponse('here the response') request_counter_signal=Signal(providing_args=['timestamp']) @receiver(request_finished) def post_request_recevier(sender, **kwargs): time=datetime.now() print("Request finished!") print('time: ',time) -
how to write status output depending on time?
How to write status output depending on time? I have a task in which I had a small problem, namely in the use of time, if less than a day has passed, then assign the status "Waiting" ('e'), if more than a day has passed, then the status "Ready" ('rd' ). Here is a part of my code, here it is just creating a ticket and immediately assigning "Waiting". Please help me with how I set the status of Waiting ('e'), if less than a day has passed, the status Ready ('rd'), if more than a day has passed. Thank you in advance for your help or for hints! class PatientAcceptVisitView(AbsPatientVie template_name = 'patient/accept_visit.html' def post(self, request, **kwargs): context = self.get_context_data(**kwargs) pk_visit = context.get('pk_visit') visit = CoreVisit.get(pk=pk_visit) visit.guid_user_patient = self.request.user.guid_user visit.type = visit.VISIT_TYPES[2] visit.date_appointment = timezone.now() visit.save() PatientConsultationTicket.objects.create(pk_visit=pk_visit, creator=self.request.user, consultation_time=visit.date_visit_start, status='e') visit_start_as_text = visit.date_visit_start.strftime("%H:%M день %d.%m.%Y") messages.info(request, f'Вы записались на {visit_start_as_text} к доктору {context.get("doctor")}') return HttpResponseRedirect(reverse_lazy('patient:visits'))