Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using DRF with an other authentication backend
i am using keycloak as IAM for my project which is a multi service project. i want to use django rest framework for my django service. i have managed to make authentication work and request.user returns an instance of User from django.contrib.auth.models, the problem is drf creates a new request object for the view, and the user authenticated by keycloak backend set in AUTHENTICATION_BACKENDS is lost, to solve this problem i have made a permission class like the following: class ClientRoleBasedPermission(permissions.BasePermission): role = "create_room" def has_permission(self, request, view): if self.role in request._request.user.get_all_permissions(): return True return False i am using this simple view to test things class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ permission_classes = [CreateRoomPermission] permission = "create_room" def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) is there a better way to solve this issue ? -
Django makemigration error No module named 'qrcode.settings'
I am trying to set up a new project on my windows 10 64 bit pc While doing python manage.py makemigrations I keep getting ModuleNotFoundError: No module named 'qrcode.settings' I have installed all the dependencies successfully, running the cmd in venv. I looked for this particular issue, but couldn't find the solution. I am using Python 3.9. The dependencies are asgiref==3.2.7 certifi==2020.4.5.1 cffi==1.14.0 chardet==3.0.4 cryptography==2.9 Django==3.0.5 djangorestframework==3.11.0 djangorestframework-jwt==1.11.0 idna==2.9 mysqlclient==1.4.6 pycparser==2.20 PyJWT==1.7.1 PyMySQL==0.9.3 PyPDF2==1.26.0 pytz==2019.3 requests==2.23.0 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.9 paypalrestsdk==1.13.1 The error is as follows Traceback (most recent call last): File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\core\checks\templates.py", line 22, in check_setting_app_dirs_loaders for conf in settings.TEMPLATES File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\zubai\Downloads\SaveTreesQR\env\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'qrcode.settings' During handling of the … -
Send list elements to POST form
I have a page where the user selects values from a <li> object and drops them in another <li> object. (This is done using jQueryUI) I'd like to send to the backend via a POST request the elements that the user selects. Currently if I print the session (print(request.POST)) it doesn't show the <li> objects. To my understanding this is correct because you'd need the <input> tag. How can I achieve this kind of behaviour? I've seen this question which is the same problem, but the answer is not complete, also it's somewhat old. View def page(request): li_dict = { 'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', } # ... # POST logic if request.method == "POST": # do stuff.. #... context = {'groups_variable_list': li_dict} return render(request, 'page.html', context=context) Html <div> <ul id="sortable1" class="connectedSortable"> {% for key, value in groups_variable_list.items %} <li value={{key}}>{{value}}</li> {% endfor %} </ul> </div> <div> <form action="" method="POST"> {% csrf_token %} <ul id="sortable2" class="connectedSortable"> <!-- list filled by user with drag&drop --> </ul> <input type="submit" name="Submit"> <!-- button for POST request --> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <!-- jQuery UI for Sortable function --> <script> // sortable jQueryUI $(document).ready(function() { $( "#sortable1, #sortable2" ).sortable({ … -
Django: ROOT_URLCONF: How to distinguish between two folders with same name with two 'urls.py'?
settings.py: From the picture, you can see that there is the path trydjango/urls.py and trydjango/trydjango/urls.py. I used the latter to import my views as the FreeCodeCamp tutorial said to do. ROOT_URLCONF is set to: ROOT_URLCONF = 'trydjango.urls'. I can't go to any of my webpages in the code below for some reason. trydjango/trydjango/urls.py: I attempted to move what I had in 'trydjango/trydjango/urls.py' to 'trydjango/urls.py' and this still did not work. I also attempted to change ROOT_URLCONF to: ROOT_URLCONF = 'trydjango.trydjango.urls',but this did not work either. What should I do here? Please advise. -
page() missing 1 required positional argument: 'number' in django
So, I am trying to add pagination to my django website. Here is the code for my view function that handles pagination: def index(request): object_list = Post.published.all() latest_post = object_list.last() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = Paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/index.html',{ 'posts':posts, 'latest_post':latest_post, 'page':page, }) I am getting an error on line 11, inside the try block. Where is the error? -
How can I build a web app using python django and a ready MYSQL workbench database? [closed]
I am fairly new to this. I created a MySQL Workbench database populated with the data and tables I want. I now want to make a Small website using django web app to get from or post onto my database using MySQL queries. I tried finding tutorials but I got lost. (I must use above methods) I am not sure what I need to do. What I have done is: Install django and start a project edit settings.py in my django project to mysql Trying to install mysqlclient What should happen next and what do I need to do and what will I use? It’s a fairly small project. -
name 'validated_data' is not defined
I am trying to serialize multiple images posted for article in JSON format in DRF class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('id','author','caption','images') def create(self, validated_date): images = self.context['request'].FILES.getlist('images') articlefinal = Article.objects.create(**validated_data) for image in list(images): m2 = ArticleImages(article=articlefinal, images= image) m2.save() return articlefinal But i am getting an error that is saying articlea = Article.objects.create(**validated_data) NameError: name 'validated_data' is not defined Does anybody know why? -
Query in query in django?
I'm trying to achieve a query but I'm just unable to do it. I have 3 entities here: Clients: class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) Courses: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre del curso", null=False, default="", max_length=200) Consumptions: class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) course = models.ForeignKey(Course, verbose_name=("Curso"), null=True, default=None, on_delete=models.SET_DEFAULT) I want to get a list with the 10 most sold courses for the client that visit the page. I want to show the client the name of the course and the number of consumptions that he has done with that course. In every consumption there is a course and a client associated. Could someone give me a hand? -
How to create two object instances from two different models with a single POST request?
I am learning the Django-Rest Framework. I want to create an object instance for both my Story model and my File model with a single post request. So the incoming data contains a title and a file. I want then to create a story object with a title and the image field contains a reference (fk) to the id of the file instance. In the File model a own instance of File is created with the incoming file data. # File Model class File(models.Model): file = models.FileField(upload_to='audio_stories/', null=True, default='some_value') # Story Model class Story (models.Model): title = models.CharField(max_length=100,blank=True) image = models.ForeignKey(File,on_delete=models.CASCADE, blank=True, default=None) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): image = serializers.FileField() class Meta: model = Story fields = ('title','image') def create(self, validated_data): image = validated_data.pop('image') title = validated_data.pop('title') image_instance = File.objects.create(file=image) story_instance = Story.objects.create(title=title, image=image_instance) return story_instance # File Serializer class TestFileSerializer (serializers.ModelSerializer): class Meta: model = File fields = ('__all__') If I send the formdata via Postman to my server it responses with "image": ["This field is required."]. If this is an obvious mistake, I apologize in advance. I am grateful for any clarification. -
Django - Implement "Remember me" after login
Could you please point me to the right direction of how to implement Remember me in my website. I read a couple of articles of how to implement but i'm more confused than point me to the right direction. I've configured the following: forms.py first_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("first name"), error_messages={'invalid': _("Wrong First Name, use only letters")}) last_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("last name"), error_messages={'invalid': _("Wrong Last Name, use only letters")}) email = forms.EmailField(required=True) remember_me = forms.BooleanField(required=False) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views.py def loginPage(request): if request.user.is_authenticated: return redirect('index') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'members/login.html', context) login.html <div class="form-group custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="remember_me" id="remember_me"> <label class="custom-control-label" for="remember_me">Remember me</label> <a class="tdu btn-fpswd float-right" href="#">Forgot Password?</a> </div> Of course above code doesn't work. Thank you! -
Factory Boy: how to set conditional SubFactory() attribute depending on params
I got a Customer model which is related to a Company model. I'd like to give my factory the possibility to use a given company (if I need several customer from the same company). I thought to use the inner class Params to achieve that, but I got an issue using LazyAttribute and SubFactory together. Here is my factory: class CustomerFactory(UserFactory): """ To be valid, customer needs to belong to one of these groups: - manager - regular This can be achieved using the `set_group` parameter. Example: manager = CustomerFactory(set_group=manager_group) """ @lazy_attribute def _company(self): if self.use_company: return self.use_company else: return SubFactory('rdt.tests.factories.CompanyFactory') class Meta: model = Customer class Params: use_company = None @post_generation def set_group(self, create, extracted, **kwargs): if extracted: self.groups.add(extracted) I thought to use the factory as: c1 = factories.CustomerFactory(use_company=my_company) c2 = factories.CustomerFactory() I got ValueError. It seems I can't get the parameter value 'use_company' in the factory. Anyway my factory throws a ValueError. -
DRF-extensions queryset use select_related,show different sql result,
I try to use DRF-extensions for the caches. but same queryset ,Will produce different sql query time, my code: view.py queryset = Users.objects.select_related('location', 'status', 'department', 'position', 'payper') no DRF-extensions# # # # # # # # # # # # # # # # # # # # def list(self, request, *args, **kwargs): result: use DRF-extensions# # # # # # # # # # # # # # # # # # # @cache_response(timeout=60 * 60, key_func=StaffListKeyConstructor()) def list(self, request, *args, **kwargs): result: is this a bug ?How can i fix it, thanks -
Return nested JSON from Models with relations in Django
models.py (simplified) class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_books(self): return Book.objects.filter(author=self.pk) class Book(models.Model): name = models.CharField(max_length=255) pages = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.author}' class Paragraph(models.Model): name = models.CharField(max_length=255) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.book}' I want to return all the instances in a json file with this structure: [ { "name": 'Dumas', "books": { "name": "The count of Montecristo", "paragraphs": { "name": "paragraph_name_1", }, { "name": "paragraph_name_2", }, { "name": "The three Musketeers", "paragraphs": { "name": "paragraph_name", }, ] What I tried: serializers.py class AuthorSerializer(serializers.ModelSerializer): books = serializers.CharField(source='get_books', read_only=True) class Meta: model = Author fields = ['name', 'books'] This add the books key but the value is the string representation of the istances of Book (of course), how I make the value being the serialized istances of Book? I have created a BookSerializer. Notes: I know that I can created a nested json by creating a serializer for Paragraph with depth = 2 but this will include fields I don't want (like pages in Book) and the json structure will be totally different. -
How to Render Django ForeignKey relation on Datatables Serverside
Im stuck for days, im using plugin django-datatables-view and I need to render ForeignKey related value in serverside datatables, it's like: {{data.pasien_id.name}} in typical django template. but that way not work with serverside datatables, and there is no documentation anywhere to achieve that. the code shown below. Models.py class Pasien(models.Model): nama = models.CharField(max_length=40, null=True) class Log_book(models.Model): pasien = models.ForeignKey(Pasien, on_delete=models.PROTECT, null=True) Views.py class logbook_json(BaseDatatableView): model = Log_book columns = ['id', 'pasien_id'] order_columns = ['id','pasien_id'] def render_column(self, row, column): if column == 'id': return escape('{0}'.format(row.id)) else: return super(logbook_json, self).render_column(row, column) def filter_queryset(self, qs): filter_customer = self.request.GET.get('search[value]', None) if filter_customer: customer_parts = filter_customer.split(' ') qs_params = None for part in customer_parts: q = Q(id__icontains=part) | Q(pasien_id__icontains=part) qs_params = qs_params | q if qs_params else q qs = qs.filter(qs_params) return qs templates.html datatables load, <script class="init" type="text/javascript"> $(document).ready(function () { $('#responsive-datatablex').DataTable({ // ... searching: true, processing: true, serverSide: true, stateSave: true, "ajax": "{% url 'logbook_json' %}", }); }); </script> -
Why after moving a .js script from html to .js file, it does not load the values?
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found), url.py: path('myapp/post/ajax/ajax_load_subtags', load_subtags, name='ajax_load_subtags'), -
generate client_secret for sign in with apple using python 2.7 and django 1.9, giving me " JWSError: Could not deserialize key data"
login.py how i geberate client secret def generate_apple_client_secret(): secret = settings.SOCIAL_AUTH_APPLE_PRIVATE_KEY year = new_date_time.now().year month = new_date_time.now().month day = new_date_time.now().day now = int(datetime.datetime(year, month, day).strftime('%s')) headers = {"alg": 'ES256', "kid": settings.SOCIAL_AUTH_APPLE_KEY_ID} claims = { "iss": settings.SOCIAL_AUTH_APPLE_TEAM_ID, "iat": now, "exp": now + int(datetime.timedelta(days=180).total_seconds()), "aud": "https://appleid.apple.com", "sub": settings.CLIENT_ID } client_secret = jwt.encode( headers=headers, claims=claims, key=secret, algorithm='ES256' ) return client_secret Internal Server Error: /ar/api/social-login/ Traceback (most recent call last): File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 285, in post user = self.login_with_apple(ser.instance.token) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 474, in login_with_apple client_secret = generate_apple_client_secret() File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 649, in generate_apple_client_secret headers=headers, claims=claims, key=secret, algorithm='ES256' File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jwt.py", line 64, in encode return jws.sign(claims, key, headers=headers, algorithm=algorithm) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 50, in sign signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 172, in _sign_header_and_claims raise … -
Bitbucket-Pipeline: How to automatically build and deploy a Django app docker image to Heroku or VPS
I'm new to docker and bitbucket pipelines so things a bit confusing at the moment when it comes to the practical implementation. I am looking for an existing walk-through (in a forum, book, article etc) about: "Bitbucket-Pipeline: How to deploy a docker image to Heroku" or, even better a source dealing with: "step by step: how to dockerize and deploy your django app via bitbucket pipelines to heroku and vps" I found one online using "Springbook" link and a shell script but I couldn't generalise it into django and docker-compose. Some posts say you cannot use docker-compose in bitbucket, and do I need to use a shell script? Any type of help or direction would be much appreciated at this stage of learning. -
Uncaught TypeError: $(...).select2 is not a function--Slect2 not working
I have include below listed js file in the head tag on an html page(index.html), after loading that page on a button click I append an html page to the current page(index.html) which contain an select box. but when i call select2 in his appended page am getting below error, Uncaught TypeError: $(...).select2 is not a function Please help to sove the issue. <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'reports/assets/plugins/bootstrap/popper.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/chartjs/chart.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/apexcharts/dist/apexcharts.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/toastr/toastr.min.js' %}"></script> <script src="{% static 'reports/assets/js/lime.min.js' %}"></script> <script src="{% static 'reports/assets/js/pages/dashboard.js' %}"></script> <script src="{% static 'reports/assets/js/chart.js' %}"></script> <script src="{% static 'reports/assets/js/pages/charts.js' %}"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/af-2.3.0/b-1.5.2/b-colvis-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/cr-1.5.0/fh-3.1.4/r-2.2.2/datatables.min.js"></script> <!-- needed to use moment.js for our date sorting--> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js" ></script> --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" ></script> <script src="{% static 'js/form_validate/jquery_validate.js' %}"></script> select2 initialized in the appended page, $(document).ajaxComplete(function() { $("select").select2(); }); Also this iisue was not there when am using select box directly in the main page itself. -
How to display a single form with Foreign Key and choices in a Django Form?
My goal is display a form with all theses fields, I'm stuck to display city and description field from City model, the first one needs to display a select box with all cities choices and the other just a text field. So, I need to display a form with this format: city (With selected box from all choices) description date status CITIES_CHOICES = (('RJ', 'Rio de Janeiro'), ('NY', 'New York'), ('PIT', 'Pittsburgh')) class City(models.Model): city = models.CharField(max_length=50, choices=CITIES_CHOICES) description = models.TextField() def __str__(self): return self.city class Checkin(models.Model): destination = models.ForeignKey(City, on_delete=models.SET_NULL) date = models.DateTimeField() status = models.BooleanField() I had create a form using Modelform but how can I display the fields from City model instead display de city object properly? Any idea where I need to go now? forms.py class DocumentForm(forms.ModelForm): class Meta: model = Checkin -
Use Prometheus next to Django and Gunicorn socket
I've deployed a Django project using gunicorn and Nginx following the Digital Ocean tutorial. Now, I'm trying to add Prometheus to monitor the performance of my application, but I'm not sure how to access the /metrics endpoint because using as a target ['localhost/metrics'] or ['localhost:8000/metrics'] values does not work. Can anyone help me, please? -
How to filter dates by range in Django Admin
class ExampleFunction(admin.ModelAdmin): list_display = ('user', 'date', 'task') list_filter = ('date',) The problem is that the builtin date filter don't let me insert a custom date, just pick some preset values like: Today, Last 7 days, ... -
Why did my Django app stop building in App Engine environment
Recently my app's deployment has stopped building and I cannot figure out why. My app is a simple app that does some calculations, I've followed deployment instructions and have the same settings from GC tutorial here. I am successfully pushing deployments but I think it is not building and launching Django. I have the Cloud Build API enabled. Any ideas on troubleshooting this would be appreciated -
I am facing issue to check answer and update user score card. my question(Objective or Descriptive type)
I am rendering one by one question from DB and using pagination for next(skip). In this model in add question ,customer and attempt question. Scoreboard models is class QuizTakers(models.Model): customer = models.ForeignKey(User, verbose_name=_("Customer"), null=True, on_delete=models.SET_NULL) questions = models.ForeignKey(Questions, verbose_name=_("Question"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("quiz"), on_delete=models.CASCADE) attempt = models.PositiveIntegerField() total_correct = models.PositiveIntegerField() question_type = models.TextField(blank=True) flag_question = models.TextField(blank=True) create_date = models.DateTimeField(_("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField(_("Last update timestamp"), auto_now=True) question quiz view is: Maybe I am doing wrong in my view file because when i hit on post request then quiz page refresh and question start again.Please advise how to check every pagination next on answer and update on score board. def Quizsession(request): quiz = Quiz.objects.get(pk=request.session['quiz']) queries = [Q(topics__id=value.id) for value in quiz.topic.all()] query = queries.pop() for item in queries: query |= item ques_query = Questions.objects.filter(query).order_by('?')[:quiz.no_of_question] questions = ques_query count=questions.count() # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(questions, 1) try: questions = paginator.page(page) except PageNotAnInteger: questions = paginator.page(1) except EmptyPage: questions = paginator.page(paginator.num_pages) context={ 'object_list': questions, 'page_obj': questions, 'count': count } if request.method =='POST': return redirect(reverse_lazy('forntend_panel:customer_quiz_start')) return render(request, 'test.html', context) -
Django-oscar manage users via dashboard
I'm not able on a fresh project with django-oscar to manage users using the dashboard(editing/deleting) - as superadmin I'm able only to see user details and also send reset password email. I didn't find any information about this. Also, I checked Django Oscar Dashboard User app and I don't see any view for this purpose. It's an easy way to handle editing/deleting users via the oscar dashboard? I can see the solution as creating a custom view for that but then I think having it just in the Django Admin will more efficient :) -
Authentication Creditial were not provided error in Django
I'm pretty new in django, especially django rest framework. so i tried to follow some instruction in the internet. but when I test it using Postman, it gives an error that says "detail": "Authentication credentials were not provided." in the json file. so what did I do wrong to be exact?