Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django returns model objects in random order after app rename
I've renamed an app in my Django project, trying to follow all 'best practices', that is, I renamed project folders, migrations (in project + PostgreSQL), DB content types and table names. Everything works fine, except one thing: the order of the objects returned by myfavmodel.objects.all() appears to be random, that is, NOT sorted by increasing ID, yet it is always the same when I call myfavmodel.objects.all(). Even more strange is that some models in the renamed app show this behaviour while others show the normal one, that is, their objects are returned sorted by increasing ID. I can solve the problem rather easily by adding ordering = ['id'] to the Meta class of my models but I would like to understand what is causing this behaviour. -
After running "python manage.pr makemigrations" indjango, models are still left un migrated with this message on CLI
It is impossible to add a non-nullable field 'core' to event without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. enter image description here my models -
How to make Django view accessible only when a GET request is issued by HTMX?
I am trying to learn HTMX for using it with Django. I have a simple HTMX button that when you click you get some filtered results on the page. The problem is that when users go to the specified URL provided for the purpose of showing content through the GET request, they can see the content of the page. They should only be able to see this content when they press the HTMX button though, not by navigating to the URL HTMX gets in order to show the content. Is there any way on how to handle this? -
How to change json view in django serializer?
This is my serializer.py class RefbookSerializer(serializers.ModelSerializer): class Meta: model = Refbook fields = ['id', 'code', 'name'] And it's my views.py class RefbookAPIList(ListCreateAPIView): queryset = Refbook.objects.all() serializer_class = RefbookSerializer def get_queryset(self): date = self.request.query_params.get('date', None) if date: query = Refbook.objects.filter(versions__date__lte=date).distinct() return query return super().get_queryset() Now, on request GET api/v1/refbooks/?date=2023-02-01 it returns a response like: [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] But i want like this: { "refbooks": [ { "id": 3, "code": "1", "name": "..." }, { "id": 4, "code": "2", "name": "..." } ] } How can i add this "refbooks" key and curly braces around it? -
Form with different target urls to send the POST to
I have one view displaying a form. Now, depending on the button the user chooses, I want to have the data processed in a different way. These "different ways" correspond with different views that I want the POST request go to. Please help me building a form with multiple buttons leading to different urls/views. <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Process form with view ONE"> <input type="submit" value="Process form with view TWO"> <input type="submit" value="Process form with view THREE"> </form> My problem here is that the action attribute of the form tag defines where this POST request is going to. How can I change that target url via multiple buttons? I know I could also handle this logic on the server-side. But the question is: Do I have to? If not, please show me the way -
Django filter query using Q
Can anyone help me. Im trying to use a django filter with Q. This is my function def get_first_time_customer_ids(year: int, month: int) -> QuerySet: return Customer.objects.filter( Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__year=year, bookings__pickup_time__month=month) & ~Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__lt=date(year, month, 1)) ).distinct().values_list('id', flat=True) What im trying to achieve is to yield all the customer id that have the first time booking for any given year and month. But its failing on my test case. My test case : def test_get_first_time_customer_ids(self) -> None: customer_1 = Customer.objects.create(name="Customer 1") customer_2 = Customer.objects.create(name="Customer 2") Booking.objects.bulk_create([ Booking(number="A", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 4, 12), route_id=1, vehicle_category_id=1), Booking(number="B", customer=customer_1, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 1, 5, 12), route_id=1, vehicle_category_id=1), Booking(number="E", customer=customer_2, price=100_000, status=Booking.STATUS.completed, pickup_time=dt(2023, 2, 10, 12), route_id=1, vehicle_category_id=1) ]) ids = get_first_time_customer_ids(2023, 2) self.assertTrue(customer_2.id in ids) self.assertFalse(customer_1.id in ids) Its failing in the last line. The customer id for customer_1 included in query, it shouldnt have. Any help is appreciated -
Django models default value based on parent length
I'm making an app that has multiple exams and multiple questions for each exam. This is my current 'Question' model: class Question(models.Model): exam = models.ForeignKey(Exam, related_name='questions', on_delete=models.CASCADE) question = models.TextField() explanation = models.TextField(blank=True, null=True) TOPICS = [ ('NA', 'Not Available'), ('Algebra', 'Algebra'), ('Geometry', 'Geometry'), ('Trig', 'Trigonometry'), ('Calc', 'Calculus'), ('Chem', 'Chemistry'), ('Geology', 'Geology'), ('Physics', 'Physics'), ('Reading', 'Reading'), ('Writing', 'Writing'), ('Spelling', 'Spelling'), ('Comprehension', 'Reading Comprehension'), ] topic = models.CharField(max_length=20, choices=TOPICS, default='NA') order = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) attempts = models.IntegerField(default=0, editable=False) correct_attempts = models.IntegerField(default=0, editable=False) class Meta: unique_together = ['exam', 'order'] def __str__(self): return f'{self.exam} - Q{self.order}' You can pretty much ignore all the fields except the 'order' field. This field shows what order the question will appear on the exam. I would like for the default value of this order field to be the number of existing questions in the exam + 1. For example, if my exam has two questions in it already, and I'm trying to add a third question, the order of this question will default to '3' unless I manually change it. I know this doesn't work, but this solution would work similarly to this line of code: default=Question.objects.filter(exam=self.exam).count() + 1 I'm inexperienced in creating functions for … -
For loop and with tag in a Django template
I have a context built in this way: def end(request): numero_debitori = request.session['numero_debitori'] dati_totali = {'numero_debitori': numero_debitori} if request.session['tipo_creditore'] == 'PF': dati_totali['creditore'] = { 'tipo': 'Persona Fisica', 'dati': { 'nome': request.session[f'nome'], 'cognome': request.session[f'cognome'], 'luogo_di_nascita': request.session[f'luogo_di_nascita'], 'data_di_nascita': request.session[f'data_di_nascita'], 'comune_di_residenza': request.session[f'comune_di_residenza'], 'indirizzo_di_residenza': request.session[f'indirizzo_di_residenza'], 'email': request.session[f'email'], 'pec': request.session[f'pec'], 'codice_fiscale': request.session[f'codice_fiscale'], 'partita_iva': request.session[f'partita_iva'], } } elif request.session['tipo_creditore'] == 'PJ': dati_totali[f'creditore'] = { 'tipo': 'Persona Giuridica', 'dati': { 'denominazione_sociale': request.session[f'denominazione_sociale'], 'comune_sede_principale': request.session[f'comune_sede_principale'], 'indirizzo_sede_principale': request.session[f'indirizzo_sede_principale'], 'email': request.session[f'email'], 'pec': request.session[f'pec'], 'codice_fiscale': request.session[f'codice_fiscale'], 'partita_iva': request.session[f'partita_iva'], } } for i in range(numero_debitori): if request.session[f'tipo_{i}'] == 'PF': dati_totali[f'debitore_{i}'] = { 'tipo': 'Persona Fisica', 'dati': { 'nome': request.session[f'nome_{i}'], 'cognome': request.session[f'cognome_{i}'], 'luogo_di_nascita': request.session[f'luogo_di_nascita_{i}'], 'data_di_nascita': request.session[f'data_di_nascita_{i}'], 'indirizzo_di_residenza': request.session[f'indirizzo_di_residenza_{i}'], 'codice_fiscale': request.session[f'codice_fiscale_{i}'], 'partita_iva': request.session[f'partita_iva_{i}'], } } elif request.session[f'tipo_{i}'] == 'PJ': dati_totali[f'debitore_{i}'] = { 'tipo': 'Persona Giuridica', 'dati': { 'denominazione_sociale': request.session[f'denominazione_sociale_{i}'], 'sede_principale': request.session[f'sede_principale_{i}'], 'codice_fiscale': request.session[f'codice_fiscale_{i}'], 'partita_iva': request.session[f'partita_iva_{i}'], } } context = {'dati_totali': dati_totali} return render(request, 'end.html', context) Inside end.html I'm trying to access to f'debitore_{i}' in this way but nothing was shown: {% for i in dati_totali %} {% with debitore_|add:i as debitore %} {{dati_totali.debitore.tipo}} {% endwith %} {% endfor %} I don't know what's wrong with this code. I also tried to print the data inside the terminal to check if the data inside the … -
WebSocket connection to failed
Locally, everything works fine. When I deploy the applications to Railway I get a "WebSocket connection to failed" error. ` application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns))), }) websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), ] const chatSocket = new WebSocket('wss://' + 'appdvibe.up.railway.app' + '/chat/' + roomName + '/'); -
displaying pics in django tempaltes unevenly
I am new to Django and I have a html template which have uneven pics but i have no idea how to do the for in my html file while getting the pics from DB. can someone please help me? this is the thing that I want? enter image description here I have no idea for this problem -
How to use different python.exe in Pipenv environment, corporate windows defender firewall, Django REST API
I have an issue where the windows defender firewall will only allow connections to python via a specific folder (e.g. C:Anaconda/python.exe) (This is a conda environment) I would like to run an API in a virtual environment, however that environment uses another folder. (e.g. C:VEnv) Rather than update the packages in the conda environment, I would much prefer the control of a virtual environment for the API, but it cannot be reached outside of the PC running it due to the PC windows firewall restrictions. Is there some sort of setting that would allow me to use the python.exe from another folder from within the venv? Am I in denial that there is any solution to this problem other than opening up the defender firewall? I have tried running the API in the virtual environment (maybe im missing a setting?) No luck. I have tried running the API in the conda environment, and a whole load of other stuff broke, which will take a long time to fix. I do have the API running from the virtual environment being accessed within its own PC, but externally there is nothing. -
Django record and save mp4
I'm new to Django. I'm trying to record a video in the browser than automatically save that to the server as an mp4 file. I managed to do it, but the videos are sent as a blob and saved in the database. But I would need an mp4 file on the server. For recording I'm using MediaRecorder. BTW this only needs to work on desktop, not on mobile. This is my js code: const videoElem = document.getElementById('stream-elem') var startBtn = document.getElementById('start-stream') var endBtn = document.getElementById('stop-media') console.log("recorder"); var recorder; const settings = { video: true, audio: true } startBtn.addEventListener('click', function (e) { console.log("StartStream button is clicked"); navigator.mediaDevices.getUserMedia(settings).then((stream) => { console.log(stream); videoElem.srcObject = stream recorder = new MediaRecorder(stream) console.log(recorder); recorder.start(); const blobContainer = []; recorder.ondataavailable = (e) => { blobContainer.push(e.data) } recorder.onerror = (e) => { return console.log(e.error || new Error(e.name)); } recorder.onstop = (e) => { console.log(window.URL.createObjectURL(new Blob(blobContainer))); var newVideoEl = document.createElement('video') newVideoEl.height = '400' newVideoEl.width = '600' newVideoEl.autoplay = true newVideoEl.controls = true newVideoEl.innerHTML = `<source src="${window.URL.createObjectURL(new Blob(blobContainer))}" type="video/mp4">` document.body.removeChild(videoElem) document.body.insertBefore(newVideoEl, startBtn); var formdata = new FormData(); formdata.append('blobFile', new Blob(blobContainer)); fetch('/upload', { method: 'POST', body: formdata }).then(()=>{ alert('streamed video file uploaded') }) } }) }) endBtn.addEventListener('click', function (e) { videoElem.pause(); … -
Advice on Django user profile edit views
I'm building a Django app that will have users and profile models associated with them and they should have the ability to edit their profile in a view. As I see there are two similar but slightly different approaches how that could be done. An UpdateView could be used that retrieves a pk from the url and then verifies if the pk corresponds to the actual authenticated user, for instance: class ProfileUpdateView(UpdateView): model = Profile fields = ['field1', 'field2'] def get_object(self, queryset=None): obj = super().get_object(queryset=queryset) if obj.user != self.request.user: # If the object user does not match the logged in user, # raise a 404 Not Found exception. raise Http404("You do not have permission to edit this profile.") return obj Or an alternative way that would check/ reference the current user via Django's authentication backend, for instance: def profile_update(request): profile = request.user.profile form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() context = {'form': form} return render(request, 'profile_update.html', context) The main question is a bit generic, hence the name 'advice' in the post title, but are there any benefits/ risks associated with one or the other way of implementing a profile edit view that one should definitely consider when choosing … -
Unapplied migrations warning with latests version of code and data
I pulled the latest version of the master branch (which is currently running in production) and downloaded a fresh dump of the production base. I restored the database, launched it locally - I get a message that I have 10 unapplied migrations. At the same time, CI / CD is configured in the project, all migrations during the deployment process are applied automatically. Where could non-applied migrations come from? I can only explain this by the fact that someone edited the table with migrations on the prod, but there may be other versions? If I try to apply the migrations locally, then the InconsistentMigrationHistory error comes out (one of the migrations was applied earlier than the one on which it depends), but this is the next problem for me (although it is obviously related to the first one) -
How to save processed excel file (by pandas) in django model?
I want user to upload its excel file, then the file will be processed with pandas and this processed will be saved in model. However, I have an error: Traceback (most recent call last): File "C:\Corrila\DJ\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Corrila\DJ\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Corrila\DJ\lemonshop\demoapp\views.py", line 108, in upload_file form.save() File "C:\Corrila\DJ\lemonshop\demoapp\forms.py", line 43, in save new = pd.read_excel(self.file) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\util\_decorators.py", line 211, in wrapper return func(*args, **kwargs) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\util\_decorators.py", line 331, in wrapper return func(*args, **kwargs) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 482, in read_excel io = ExcelFile(io, storage_options=storage_options, engine=engine) File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 1652, in __init__ ext = inspect_excel_format( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\excel\_base.py", line 1525, in inspect_excel_format with get_handle( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\common.py", line 713, in get_handle ioargs = _get_filepath_or_buffer( File "C:\Corrila\DJ\venv\lib\site-packages\pandas\io\common.py", line 451, in _get_filepath_or_buffer raise ValueError(msg) Exception Type: ValueError at /upload/ Exception Value: Invalid file path or buffer object type: <class 'type'> I have modelform to upload an excel file and process it in pandas: ModelForm: class FileForm(forms.ModelForm): file = forms.FileField class Meta: model = FilesModel fields = ['title', 'file'] def save(self, commit=True): m = super(FileForm, self).save(commit=False) # do custom stuff if commit: new = pandas.read_excel(self.file) new = new.mean().to_excel self.file = new m.save() … -
decorator action in generics
i need to add action decorator from rest_framework.decorators to view on generics views.py class AnswerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsOwnerOrAdminOnly] queryset = Answer.objects.all() serializer_class = AnswerSerializer @action(['POST'], detail=True) def like(self, request, pk=None): answer = self.get_object() author = request.user serializer = AnswerReviewSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: answer_review = AnswerReview.objects.get(answer=answer, author=author) answer_review.delete() message = 'disliked' except AnswerReview.DoesNotExist: AnswerReview.objects.create(answer=answer, author=author) message = 'liked' return Response(message, status=200) urls.py from django.urls import path from . import views urlpatterns = [ path('answers/', views.AnswerCreateView.as_view()), path('answers/<int:pk>/', views.AnswerDetailView.as_view()), path('comments/', views.CommentCreateView.as_view()), path('comments/<int:pk>/', views.CommentDetailView.as_view()), path('answers/<int:pk>/like/', views.AnswerDetailView.like), ] i've tried on ModelViewSet and it works but how can i do it on generics? also i need my urls for like button look like this: urlpatterns = [ path('answers/<int:pk>/like/', <view>), ] -
Using fakeredis in a Django development settings file?
My Django settings.py file contains the following configuration options: # Caches CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } # Queues RQ_QUEUES = { 'default': { 'HOST': 'redis', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 360, }, } Both CACHES and RQ_QUEUES contain configuration details that point to a redis server. Is it possible to reconfigure these settings to point to an instance of fakeredis instead ? I have reviewed the fakeredis documentation and so far I have only seen examples where the redis connection is manually over-ridden, every time a call to redis is made. It seems to me that when running tests, it would be much more convenient to simply point the Django CACHE location directly to fakeredis. Is this possible? -
How customize chooser views and add a specific widget to a field using wagtail-generic-chooser
I want to override the basic view in the Article snippet selector, which does not display the checkbox correctly. class ArticleChooserMixin(ModelChooserMixin): def get_edit_item_url(self, item): # for Wagtail 4.x return reverse( "wagtailsnippets_app_name_article:edit", args=(quote(item.pk),) ) class ArticleChooserViewSet(ModelChooserViewSet): icon = "user" model = Article page_title = _("Choose a article") per_page = 10 order_by = "title" fields = ["title", "body", "url", "categories", "countries"] chooser_mixin_class = ArticleChooserMixin piece of code from the Article model from dal import autocomplete ... @register_snippet class Article( DraftStateMixin, RevisionMixin, index.Indexed, ClusterableModel, Orderable, SourceDataMixin, ): ... categories = ParentalManyToManyField("app_name.ArticleCategory", blank=True) countries = ParentalManyToManyField("app_name.Country", blank=True) ... FieldPanel("categories", widget=autocomplete.ModelSelect2Multiple()) FieldPanel("countries", widget=autocomplete.ModelSelect2Multiple()), ... Similar problem: https://github.com/wagtail/wagtail-generic-chooser/issues/65 View from the snippet creation how I want it to look and form elements that display the currently selected item current problem -
How can I measure code coverage of API integration tests?
In my company we have a Django project that has API endpoints. We are using Pytest as testing framework and some of our tests executing requests to such endpoints using requests.Session(). For example: The test is perform a GET request to /api/account/data content of root/dir/tests/test_api.py def test_some_api(self): client = requests.Session() response = client.get('/api/account/data') assert response.status_code == 200 When performing the request, the backend execute this function: ` root/models/account/api.py def user_data(request, format=None): """ @api {get} /api/account/data """ if request.method == "GET": return APIResponse(code=200) We would like the measure the code executed in `user_settings` by the test, but I failed to make it work. We are using: coverage==4.5.4 # forced to use an old version as we have dependencies conflict pytest-cov==2.10.1 To measure coverage I run this command from root pytest -v --cov-report html:html-report --cov=dir --cov-config=dir/.coveragerc .coveragerc - has only files to exclude I verified in backend logs that when the test runs, it execute the if block inside user_settings I have tried adding this code to conftest.py as written in coverage docs, but it still didn't measure user_settings code execution. @pytest.fixture(scope='session', autouse=True) def run_cov(): process = coverage.process_startup() source_path = os.path.join(_home_path, "/models/account") cov = coverage.Coverage(config_file='root/.coveragerc', source=[source_path]) cov.start() yield cov # Tests runs … -
Django, Unable to view certain database information
I've been working on a project and I've been stuck for over a week and haven't been able to find the solution to this problem. I'm creating a school management app. I've successfully allowed the teachers to create a schedule, allowed the students to view it and select it as part of their class. The problem I'm running into is that the teacher is not able to see the students information after they've chosen a class. For models I have: class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) englishName = models.CharField(max_length=200) studentName = models.CharField(max_length=200) studentId = models.CharField(max_length=200) birthday = models.DateField() gender = models.CharField(max_length=6) gradeLevel = models.CharField(max_length=8) since = models.DateField() duration = models.CharField(max_length=3) contactNumber = models.CharField(max_length=13, default=00000000) email = models.EmailField(max_length=200, default='address@email.com') def __str__(self): return self.studentName def index(request): data=Student context = {'form': data} return render(request, 'student-information.html', context) class Schedule(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateField(null = True, blank = True) time = models.TimeField(null = True, blank = True) duration = models.TextField(null = True, blank = True) capacity = models.PositiveSmallIntegerField(default=1) student = models.ForeignKey(Student, null = True, on_delete=models.CASCADE) def __datetime__(self): return self.date + '' + self.student def index(request): data = Schedule context = {'form': data} return render(request, 'set-schedule.html', context) For my views file I … -
How to merge Django queryset result, collecting values from matching keys?
My Views.py context['user'] = User.objects.filter(code='01').values('name', 'phone') print(context['user']) The current results are as follows: <QuerySet [{'name': 'John', 'cellphone': '1234567890'}, {'name': 'Doe', 'cellphone': '1234512345'}]> How can I get a result like this from templates? {% for u in user %} <span>name :</span> <span> {{ u.name }} / </span> <span>cellphone :</span> <span> {{ u.cellphone }}</span> {% endfor %} # want result name : John, Doe / cellphone : 1234567890, 1234512345 -
Gunicorn fails to spawn new worker, 3 hour hang between booting and exiting worker
I had a server outage overnight, these are the gunicorn logs (2 workers). [2023-02-13 22:17:30 +0000] [27553] [DEBUG] GET /users [2023-02-13 22:18:30 +0000] [30798] [CRITICAL] WORKER TIMEOUT (pid:27553) [2023-02-13 22:18:31 +0000] [30798] [WARNING] Worker with pid 27553 was terminated due to signal 9 [2023-02-13 22:18:31 +0000] [27997] [INFO] Booting worker with pid: 27997 [2023-02-14 02:27:04 +0000] [27997] [INFO] Worker exiting (pid: 27997) [2023-02-14 02:27:04 +0000] [27554] [INFO] Worker exiting (pid: 27554) [2023-02-14 02:27:04 +0000] [30798] [INFO] Handling signal: term [2023-02-14 02:27:04 +0000] [30798] [WARNING] Worker with pid 27554 was terminated due to signal 15 [2023-02-14 02:27:04 +0000] [30798] [INFO] Shutting down: Master [2023-02-14 02:28:07 +0000] [826] [DEBUG] Current configuration: config: ../config_live.py ... [2023-02-14 02:28:07 +0000] [826] [INFO] Starting gunicorn 20.1.0 [2023-02-14 02:28:07 +0000] [826] [DEBUG] Arbiter booted [2023-02-14 02:28:07 +0000] [826] [INFO] Listening at: unix:/run/gunicorn_live.sock (826) [2023-02-14 02:28:07 +0000] [826] [INFO] Using worker: sync [2023-02-14 02:28:07 +0000] [902] [INFO] Booting worker with pid: 902 [2023-02-14 02:28:07 +0000] [908] [INFO] Booting worker with pid: 908 [2023-02-14 02:28:07 +0000] [826] [DEBUG] 2 workers [2023-02-14 02:28:10 +0000] [902] [DEBUG] GET /users I'm trying to interpret the logs: "pid 27553 was terminated" - worker #1 crashed, outage starts "Booting worker with pid: 27997" - … -
Create super user in Django
In Django - Python, When I tried to create superuser with Django : Email : Password : Password : " CommandError: La valeur « » doit être soit True (vrai), soit False (faux). " I can't connect to my Django admin and create a new super user. I tried : Alter the file settings.py adding allauth. Not worked. python manage.py makemigrations and python manage.py migrate. Not worked. Someone has an idea ? -
Show querys data instead of model with django-ajax-datatable
I'm trying to show a the result of Django query using the module django-ajax-datatable. According to the documentation (Ajax datatable documentation)the attributes model und column_defs are at least needed to define the table. The problem is that I wanted to show a query based on some joins where the result is not based on a specific model but on a lot of attributes coming from different tables and even calculation which are only present in the query and in no table at all. As the model is mandatory, but I cannot/don't want to define a model, i don't know what to assign for the model. Everything a tried with generic names or datatypes etc. failed. For example: Query: query_result = (Model1.objects.filter(model2__id=3) .order_by("id") .values("id", "name", "model2__start", "model3__number", ) ) Datatable class: class ExampleDatatableView(AjaxDatatableView): """.""" model = *Shouldbeaquery* title = datatable_example initial_order = [["id", "asc"], ] length_menu = [[10, 20], [10, 20]] search_values_separator = '+' column_defs = [ #AjaxDatatableView.render_row_tools_column_def(), {'name': 'id', 'visible': True, }, {"name": "name", "visible": True, }, {'name': 'start', 'visible': True, }, {'name': 'number', 'visible': True, }, ] -
PyTest warning - RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path()
when i'm using pytest to run test cases i'm getting 10 warnings - RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^password/reset/$', PasswordResetView.as_view(), RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^login/$', LoginView.as_view(), name='rest_login'), 10 warnings like this. using django==3.2.4 djangorestframework==3.12.4 pytest-django==4.5.2 tried filterwarnings in setup.cfg