Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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')) -
return type of annotate
I want to get date when first order was placed for each item in database. filter = Q(prev_order_items__order_id__order_type='Normal') & Q(prev_order_items__order_id__final_approval='Yes') f_date_ord = F('prev_order_items__order_id__created_at') event_queryset3 = OrderItemTable.objects.filter(filter).annotate(f_date=Min(f_date_ord)) event_queryset3 = OrderItemTable.objects.annotate(f_date=Min(f_date_ord, filter=filter)) -
How do i compare JSON with my data from request in django?
I created API but also i must have taken JSON file from request. I just dont know how to i compare that file with data which i have in my project and how to i response it back if its true or false. I cant complete my code. i tried some codes like: def send_json(request): json_data = {'existing_binaries': ['firmware-0.3', 'cfirmware-0.6', 'firmware-0.1', 'efirmware-0.7', 'dfirmware-0.7', 'firmware-0.2', 'firmware-0.4']} #data = json.loads(request.body) serializer = CloudSerializer (json_data,many = True) if serializer.to_representation(json_data): return JsonResponse (serializer.data, print('upload et') ,safe = False) else: return JsonResponse(print('olmadı'),safe = False) def send_json(request): data = Cloud.objects.all() serializer = CloudSerializer (data, many = True) return JsonResponse (serializer.data, safe = False) -
django customize truncatechars
I'm using truncatechars but it have a problem; For example, content is: Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature using truncatechars:160 Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin litera {% block description %}{{ content|truncatechars:160 }}{% endblock %} I want like this: Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin If the word has reached the limit of 160 letters before the end of that word, don't include that word -
After migrating the models in django, I am unable to see the data in admin panal
I am trying to solve this problem whole day. My code is shown below. Actually, I created my tables in Pgadmin4. I created the table "atmpokhara" having 10 columns with id field as varchar(20) datatype. After that, I drop the id filed from my atmpokhara table. I render this table to django model using python manage.py inspectdb > models.py All the row are already in tables. Everything is going good, but when I try to open my table inside my admin panel, I get following error: operator does not exist: character varying = bigint LINE 1: ...number" FROM "atmpokhara" WHERE "atmpokhara"."id" = 57173664... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: http://localhost:8000/admin/webmap/atmpokhara/5717366409/change/ Django Version: 2.1.7 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = bigint LINE 1: ...number" FROM "atmpokhara" WHERE "atmpokhara"."id" = 57173664... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Location: D:\coding time\Django+ GeoDjango\Django Enviroment\venv\lib\site-packages\django\db\backends\utils.py in _execute, line 85 Python Executable: D:\coding time\Django+ GeoDjango\Django Enviroment\venv\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\Tekson\\Desktop\\Web-GIS-Django\\Project', 'C:\\Program Files\\Hexagon\\ERDAS IMAGINE ' '2015\\usr\\lib\\Win32Release\\python', 'C:\\Users\\Tekson\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', … -
building a quiz app local variable 'answer_selection' referenced before assignment
hey guys so I'm trying to build an app which manage an electronic quizzes, the model is right works perfectly fine when I try to add a question but the problem is when I try to post the user answers it wont work I tried so hard to fix it but couldn't! models.py class Question(models.Model): course = models.ForeignKey(CourseType, default=1, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, default=1, on_delete=models.CASCADE) answer = models.CharField(max_length=50, default="") question = models.TextField(max_length=200,default="") option1 = models.CharField(max_length=50,default="") option2 = models.CharField(max_length=50, default="") option3 = models.CharField(max_length=50, default="") option4 = models.CharField(max_length=50, default="") def __str__(self): return self.question forms.py MULTIPLE_CHOICE= [ ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'),] class TestForm(forms.Form): right_answer= forms.CharField(widget=forms.RadioSelect(choices=MULTIPLE_CHOICE)) views.py def test_view(request, question_id): if request.user.is_anonymous: return redirect('cal:signin') form = TestForm() if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): right_answer = form.cleaned_data['right_answer'] quiz = form.save(commit=False) answer_selection = Question.objects.get(id=question_id.answer) scores = 0 for find_right_answer in answer_selection: if find_right_answer == option1 or find_right_answer == option2 or find_right_answer == option3 or find_right_answer == option4: find_right_answer = Question.objects.filter(id=question_id) scores += 1 else: scores -= 1 quiz.save() return redirect('cal:quiz-page') context = {'form':form,'answer_selection':answer_selection} return render(request, 'cal/quiz_page.html', context) quiz_page.html {% extends "cal/base.html" %} {% load crispy_forms_tags %} {% block title %}Quiz !t{% endblock title %} {% block content %} <br> … -
How to Redirect to login if not authenticated in django?
I am making a forum site where if a user is not logged in, he or she will be redirected to login page. But I don't understand how to do it. -
TypeError: cannot unpack non-iterable bool object
When I run the code it redirects and showing TypeError at /accounts/register cannot unpack non-iterable bool object The problem is when I put the below condition in my code User.objects.filter(username==username).exists(): User.objects.filter(email=email).exists(): Please help from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth # Create your views here. def register(request): if request.method == 'POST': last_name = request.POST['Last_name'] first_name = request.POST['first_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.objects.filter(username==username).exists(): print("username taken") elif User.objects.filter(email=email).exists(): print('email exists') else: user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() print('User Created') else: print('password doesnt match') return redirect('/') else: return render(request,'accounts/register.html') TypeError: cannot unpack non-iterable bool object [16/Jul/2019 17:51:22] "POST /accounts/register HTTP/1.1" 500 98878 -
django translate text inside html tags and maintain html tags
I've found a tool I can use to translate text googletrans this is how it works from googletrans import Translator translator = Translator() result = translator.translate(text, dest=lang) print(result.text) but in the case that my text might come from django-ckeditor so it includes html tags for example <h1>Some Title</h1> <p>Some Text</p> I need to pass this text to it and still maintain the html tags, so far it tends to break that symetry and the text formatting gets ruined to mention it fails to translate correctly. There's tools like beautiful soup that can help you read html text, that direction looks like it's going to be bloated code that "barely" works, I'm curious if someone knows of a way to get it to work more cleanly. -
How to change the parent page?
I have custom view and form for article page in admin single view. In form I have html5 select for change parent (section). How to change the parent page in admin edit view? i try ty use edited wagtail.admin.views.pages.edit: #wagtail code revision = page.save_revision( user=request.user, submitted_for_moderation=is_submitting, ) #my code new_parent_page_id = request.POST.get('parent_page_id') if int(new_parent_page_id) != parent.id: parent = SectionPage.objects.get(id=new_parent_page_id) page.move(parent, pos='last-child') page.save() and it doesn't work wagtail==2.4 -
CS:GO Roulette Game Script
What is needed to develop a roulette game? I'm python developer and I'm also making websites with django. I have front end knowledge of css js jquery vs.. (The roulette game I want is like https://csgoempire.gg/)