Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the last record by id in Django Serializer not working properly
I am trying to get the last recorded ID in ActiveSession class. I have tested the below view and it is showing the normal results in normal page but when I try to implement the same to my API i keep getting 'ActiveSession' object is not iterable Here is the model: class ActiveSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) log = models.ManyToManyField(Log, related_name='savedlogs') Here is the serializers.py class ActiveSessionSerializer(serializers.ModelSerializer): class Meta: model= ActiveSession fields = '__all__' Here is the api.views @api_view(['GET']) @permission_classes([AllowAny]) def getActiveSession(request, **kwargs): user = get_object_or_404(User, username=request.user) print(user) last_active_session = ActiveSession.objects.filter(user=user).latest('id') serializer = ActiveSessionSerializer(last_active_session, many=True) print(serializer) return Response(serializer.data) here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\User\Desktop\Project\api\views.py", line 67, in getActiveSession return Response(serializer.data) … -
Django IntegrityError: NOT NULL constraint failed with NULLABLE field
When trying to create a superuser in Django, I'm getting the error: django.db.utils.IntegrityError: NOT NULL constraint failed: b3ack_investoruser.watchlist I have a custom user and, the only custom field IS NULLABLE: class InvestorUser(AbstractUser): id = models.AutoField(primary_key=True) watchlist = models.JSONField(default=None, blank=True, null=True) manage.py has: AUTH_USER_MODEL = 'b3ack.InvestorUser' admin.py has: from django.contrib import admin from .models import InvestorUser # Register your models here. admin.site.register(InvestorUser) I have tried python3 manage.py sqlflush I have redone all my migrations. I have deleted previous migrations. None of that works. -
What side effects will come from overriding a custom model manager's create() method?
I am implementing custom model managers, and it looks like the rest_framework by default calls the create() method of a model manager from within its serializer to create a new object. To avoid creating custom views when using a custom model manager, it seems like I could just override the create() method of my custom model manager, and implement standard ViewSets without any customization, but I don't fully understand what side-effects, if any, this will cause. Do I have to call super().create() within the overridden function to get other pieces of django to behave properly? I cannot find anywhere in the django documentation about overriding a custom model manager's create() method, which leads me to think they did not consider it as a use case, and there may be unintended consequences. Is this the case? Why does the standard recommendation seem to be to create a new create_xxx method inside the custom model manager? (i.e. creating a custom user model manager) -
Django manage.py migrate errors
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I don't understand what to do because it was working fine before. Please can someone help I so frustrated and annoyed that I've broken it after so many hours of work. Sorry I know this error code is long but I don't know which part is important. Error code `Operations to perform: Apply all migrations: admin, auth, contenttypes, network, sessions Running migrations: Applying network.0019_alter_follower_user...Traceback (most recent call last): File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 21, in main() File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
"DateTimeField %s received a naive datetime (%s)
'2022-11-11' this is the input value getting from the front end, RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active. this is the error that coming paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat() this is how i tried to convert the date, and not working, i got this error before, and i added 'tz=datetime.timezone.utc' , it was workin fine then offer.expiry=datetime.datetime.now(tz=datetime.timezone.utc)+datetime.timedelta(days=28) but how can i add tz in strptime ?? -
Django admin date time helpers missing
I have a model that includes a datetimefield... # Create your models here. class BroadcastNotification(models.Model): message = models.TextField() broadcast_on = models.DateTimeField() sent = models.BooleanField(default=False) class Meta: ordering = ['-broadcast_on'] In the admin pages the helpers for that field have gone away. I don't know what I did to cause it as I didn't test everything after every change. I did do collectstatic fairly recently if that might be the cause. -
Django - How to compare different models with same foreign key
I'm really stuck in how to do this and appreciate the help. I have three models, two of them shares the same foreign key field: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True,) name = models.CharField(max_length=100, unique=True,) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) class Revenue (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) receipt_date = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) And I have this view that annotates the sum for each model by the foreign key name with a form that filters by date: def proj_planning(request): form = ProjectionFilterForm(request.POST or None) # some definitions for the form planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by('accountplan__code').filter( month__range=[start_date, planned_end_date]) done = Revenue.objects.values('accountplan__name').annotate(Sum('amount')).filter( receipt_date__range=[start_date, end_date],).order_by('accountplan__code') if request.method == 'POST': planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by( 'accountplan__code').filter(month__range=[start_date, planned_end_date], accountplan__name__icontains=form['accountplan'].value()) done = Revenue.objects.values('accountplan__name').annotate( Sum('amount')).filter(receipt_date__range=[start_date, end_date], accountplan__name__icontains=form['accountplan'].value()) comp_zippedlist = zip(planned, done) return render(request, 'confi/pages/planning/proj_planning.html', context={ 'form': form, 'list': comp_zippedlist, }) The code kinda works (it doesn't throw any errors), but the thing is, I will never have an exact amount of data for each model. For example: if I have 6 different records in the Planning model, but only 4 records in the Revenues model, the zipped list will only show the 4 records in the Revenues and not the … -
Axios POST method with React shows as Anonymous user and CORS error in Django Backend
I have been succesfully using GET methods with Axios while the logged in user information is succesfully transmitted to backend with the following code : await axios({ method: 'get', url: BASE_BACKEND_URL + `/project/` + project_uuid + `/`, data: {}, headers: { 'Content-Type': 'application/octet-stream' }, withCredentials: true, }) class ProjectView(APIView): def get(self, request, uuid): logging.info("ProjectManifest GET begin") user = request.user print(user) When I use a similar code with the POST API call of the same function, Django backend shows the request has been requested by an anonymous user instead of the logged in user. The code for the POST command is below: await axios({ method: 'post', url: BASE_BACKEND_URL + '/project/' + project_uuid + '/', data: { project_uuid : projectJSON }, headers: { 'Content-Type': 'application/json', }, withCredentials: true, }) class ProjectView(APIView): def post(self, request, uuid): logging.info(f"ProjectManifest POST begin: {request.user}") How can I make the react axios post call to work properly with Django backend ? -
Django-filter pagination only the first search filed failed
I'm using django-filter with pagination, as long as the search filed is in the first place in filter.py -> fields = ['name_procss','typeLevel'] list, the pagination for filter of that filed will not work. fitler.py: import django_filters from MyCore.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(self,filed): return tuple((l, l) for l in list(MyRunStats.objects.exclude(**{filed: None}).values_list(filed, flat=True).distinct())) name_procss = django_filters.ChoiceFilter(label='Process',choices=tuple,null_label='None',null_value='null') typeLevel = django_filters.ChoiceFilter(label='Message Type',choices=tuple,null_label='None',null_value='null') class Meta: model = MyRunStats fields = ['name_procss','typeLevel'] def __init__(self, *args, **kwargs): super(MyRunStatsFilter, self).__init__(*args, **kwargs) self.filters['name_procss'].extra['choices'] = self.gen_choice('name_procss') self.filters['typeLevel'].extra['choices'] = self.gen_choice('typeLevel') Views.py def runstat_hist_view_render(request): all_obj = MyRunStats.objects.all().order_by('-create_dttm') hist_filter = MyRunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs[:57], 20) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'My/My_runstat_hist.html',context) html: <form method="get" > {{ filter.form}} <button type="button" onclick="submitFilter()" id="hist-search-button" >Search Message</button> </form> {% for item in response %} <nav> <ul class="pagination"> {% if response.has_previous %} <li><a href="?page=1&{{ request.get_full_path }}">&laquo; First</a></li> <li ><a href="?page={{ response.previous_page_number }}&{{ request.get_full_path }}">Previous</a></li> {% else %} <li><a href="#">Previous</a></li> {% endif %} {% for num in response.paginator.page_range %} {% if response.number == num %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% elif num > response.number|add:'-3' and num < response.number|add:'3' %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% endif %} {% endfor … -
Connecting html with css using django
This is the html file that i'm trying to add a star rating for book_detail.html {% extends "base.html" %} {% load static %} {% block title %} Block Detail Page {% endblock title %} {% block sidenav %} {% for item in item_list %} <li> <a href="{{ item.link }}"> {{ item.item }} </a> </li> {% endfor %} {% endblock sidenav %} {% block content %} <h1 align="center"> Book Detail </h1> <table align="center" border="2" width="400"> <tr> <td> {{ book.name }} </td> </tr> <tr> <td> <img src="{% static book.pic_path %}" width="100"> </td> </tr> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <tr> <td> {{ book.username }} <div id="full-stars-example"> <div class="rating-group"> <input class="rating__input rating__input--none" name="rating" id="rating-none" value="0" type="radio"> <label aria-label="No rating" class="rating__label" for="rating-none"><i class="rating__icon rating__icon--none fa fa-ban"></i></label> <label aria-label="1 star" class="rating__label" for="rating-1"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-1" value="1" type="radio"> <label aria-label="2 stars" class="rating__label" for="rating-2"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-2" value="2" type="radio"> <label aria-label="3 stars" class="rating__label" for="rating-3"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-3" value="3" type="radio" checked> <label aria-label="4 stars" class="rating__label" for="rating-4"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-4" value="4" type="radio"> <label aria-label="5 stars" class="rating__label" for="rating-5"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-5" value="5" type="radio"> </div> </div> </td> </tr> </table> {% … -
Problems filtering columns that have many rows with a None value(Django database)
I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value. Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value. I want to know if there is any problem when filtering columns that have many None values and why this might be happening -
web form where you can upload a pdf file and it gets translated into visible text
I'm trying to figure it out how to do it with python and Django or flask. I want to make a website where you can upload a pdf file and it gets translated into visible text, and I need to use specific keywords from pdf file and assign them with translation of my own words and then display it to the user. Is something like that possible with python? -
Two views same URL
I have a single dashboard_view URL path("", view=dashboard_view, name="dashboard"). On this page you can see the homepage unauthenticated. However, if you login, I present a modal popup to allow a user to populate a CreateForm. The issue is that the dashboard_view doesn't have the form ( I have that in another view ). What is the best practice for this? Best for the user to have different options on the same page without having to switch pages. -
{% csrf_token %} django error in speech recognition
I have coded using JavaScript for voice search using speech recognition. In the html form, if I have loaded 'csrf' token for post form, the speech recognition is not working. It is working when there is no 'csrf' token. Why there is an issue like this? Here is my Html page for form. <form action="{% url 'voice' %}" method="post" id="search-form"> {% csrf_token %} <input name="q" type="text" placeholder="Search" autocomplete="off" autofocus> <!-- <button type="button"><i class="fas fa-microphone"></i></button> --> </form> -
Python Django - Passing in multiple parameters to Factory during testing
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). For this project, I'm working on functionality where a user will get an error if they try to invite someone who is already in the app (meaning people who are already in the app's database). I'm working on unit tests that ensures the error messages pop up when users are detected as already existing. I managed to get my first scenario working, but I'm a bit stumped for the second one. Here is a file that is central to both tests. factories.py class ChannelFactory(factory.django.DjangoModelFactory) class Meta: model = Channel id = int name = str class CurrentUserFactory(factory.django.DjangoModelFactory) class Meta: model = CurrentUser user_email = user_email channel = models.ForeignKey(Channel) Scenario #1 (currently working) - one new user is invited to join the app but already exists in the app's database test_forms.py from tests.factories import ChannelFactory, CurrentUserFactory @pytest.mark.django_db def test_that_current_user_cannot_be_reinvited(email, error_message): """user that is already in the specific channel cannot be reinvited""" email = "user@test.com" error_message = "user@test.com already exists in this channel" # I am not specifying the … -
What causes text to have an odd character at the end
I am using the django standard base.html with the following {% load i18n static %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" dir="{{ LANGUAGE_BIDI|yesno:'rtl,ltr,auto' }}"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Font Awesome CSS --> <script src="https://kit.fontawesome.com/5135d630a7.js" crossorigin="anonymous"></script> <title>{% block title %}{% endblock %}</title> This is giving me the following header with Home and Admin Pages having an odd character at the end. Is it the font? -
how to read json file array objets with python flask
I have a problem with read a file JSON, that file contains an array objects like this: [{"some": 1, "list": [{"one":1}]},{"some": 1, "list": [{"one":1}]}] my code is like below: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) show me this error: I try to read that file and put that file in ls_plano to read and assign to the other values like this: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) if ls_plano is not None: for plano in ls_plano: temp_plano = {} temp_plano["inPlanoPersonalizado"] = plano.get("inPlanoPersonalizado") temp_plano["inSelecionado"] = plano.get("inSelecionado") if plano.get("lsChassi"): temp_plano["lsChassi"] = self.__map_ls_chassi(plano.get("lsChassi", [])) if plano.get("lsTipoObjetoSegurado"): temp_plano["lsTipoObjetoSegurado"] = self.__map_ls_tipo_ob_segurado( plano.get("lsTipoObjetoSegurado") ) if plano.get("lsComissao"): temp_plano["lsComissao"] = self.__map_ls_comissao(plano.get("lsComissao", [])) if plano.get("lsParcela"): temp_plano["lsParcela"] = self.__map_ls_items(plano.get("lsParcela", [])) temp_plano["nmIdentificadorPlano"] = plano.get("nmIdentificadorPlano") temp_plano["nmPlano"] = plano.get("nmPlano") temp_plano["nrPlano"] = plano.get("nrPlano") temp_plano["vlAdicionalFracionamento"] = plano.get("vlAdicionalFracionamento") temp_plano["vlAssistenciaFacultativa"] = plano.get("vlAssistenciaFacultativa") temp_plano["vlCobranca"] = plano.get("vlCobranca") temp_plano["vlComercial"] = plano.get("vlComercial") temp_plano["vlIof"] = plano.get("vlIof") temp_plano["vlPremioLiquido"] = plano.get("vlPremioLiquido") temp_plano["vlPremioNet"] = plano.get("vlPremioNet") temp_plano["vlPremioTarifa"] = plano.get("vlPremioTarifa") temp_plano["vlPremioTotal"] = plano.get("vlPremioTotal") temp_plano["vlTotalComissao"] = plano.get("vlTotalComissao") temp_plano["vlTotalDesconto"] = plano.get("vlTotalDesconto") resp.append(temp_plano) return resp please help me, thanks for your attention. -
What does django's Manager.create() method do?
I was poking around in the rest_framework trying to figure out how it works, and came across a call to Model.objects.create(), but I can't for the life of me find the create() method for django model managers in the docs or the source code. It looks to be dynamically generated. What does it do, exactly? Where can I find its code? If I wanted to override it, what would my implementation have to do? I found this question but it only says to call the super().create() method. -
Django crispy form is not posting or view is incorrect
I am currently working on a note/comment system. It is intended to work as adding notes to each individual projects. For example, you set up a "Project" and there is a note or comment sections intended for adding updates to the project. Here is my view.py for updating the project. The top portion is for updating the project itself, the bottom portion is for adding the notes. @login_required(login_url="/login") def update_project(request, pk): queryset = DevProjects.objects.get(id=pk) form = UpdateProject(instance=queryset) if request.method == 'POST': form = UpdateProject(request.POST, instance=queryset) if form.is_valid(): form.save() return redirect('/') project = get_object_or_404(DevProjects, id=pk) notes = project.notes.filter(id=pk) new_note = None if request.method == 'POST': notes_form = AddProjectNotes(request.POST, instance=project) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.project = project new_note.save() else: notes_form = AddProjectNotes() return render(request, 'projects/updateprojects.html', {"form": form, "queryset": queryset, 'project': project, 'notes': notes, 'new_note': new_note, 'notes_form': notes_form}) Whenever I try and submit the notes, it shows that is successfully posted to DB but in DB there is no entries. Here is my template. <div class="container"> {% if new_note %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="post"> {{ notes_form.notes|as_crispy_field }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} </div> <div class="container"> … -
Django to Droplet: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I am getting Internal Server Error while setting up GNINX... On both the domain and on the droplet IP: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Correct response was give by: curl --unix-socket /run/gunicorn.sock localhost also sudo systemctl status gunicorn works as expected Gunicorn bind als worked on both the droplet IP and the domain. There is just something going on with GNINX. So I gues it has something to do with the file settings. Tried to reinstall the Droplet multiple times, Tried different settings and groups already, Nothing seems to work. -
How to implement sending a command from a page to Django via SSH?
How to implement sending a command from a page to Django via SSH? It is necessary that the page has a button that, when clicked, sends a command via SSH to the Ubuntu virtual machine. Good afternoon. Question regarding the implementation of SSH on pages in Django. It is necessary to assemble the command over SSH to the server. There is such code using Paramiko: views.py class StartServer(server, view): def get(self, request, *args, **kwargs): form = AddServerForm(request.POST or None) servers = server.objects.all() context = {'form': form, 'csservers': servers} return render(request, 'csservers/server_detail.html', context) # def post(self, request, *args, **kwargs): # pass def start_server(i, request, pc): print(request.POST) if request.POST: server = Server.objects.get(id=pk) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=server.host, username=server.server_username, password=server.secret, port=server.port) standard input, standard output, standard output = client.exec_command('./<command>') data = stdout.read() + stderr.read() client.close() HTML: <!DOCTYPE html> <html lang="en"> <head> <metacharset="UTF-8"> <title>Title</title> </head> <body> {{server.host}} {{server.port}} {{server.server_username}} {{server.secret}} <form action="{% url 'server_start' server.slug server.id %}" method="post"> {% csrf_token %} <button type="submit" style="outline: none; border: none; background-color: red; color: #fff;">Start server</button> </form> </body> </html> If I click on the button, it gives an error 405. I need to connect to the local Ubuntu machine via SSH and send the ./ command. Is it … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work with Firefox 107 or Chrome 107
With Firefox 107.0 in Win 10, in settings.py, I have SESSION_EXPIRE_AT_BROWSER_CLOSE = True In Storage in Firebug, I see the sessionid cookie with Expires/Max-Age: Session. When I close Firefox and restart it, the cookie is still there and so is my session information. I can manually delete the sessionid cookie. Is there something else I need to do or know? -
I keep getting "TypeError __init__() takes 1 positional argument but 2 were given" in my code but the urls and views are correct?
In Django, I am trying to create 2 new pages. I have created other pages using this similar approach. Here is my code for views.py and urls.py: views.py class practice_spanish(TemplateView): template_name = "practice_spanish.html" class quiz_spanish(TemplateView): template_name = "quiz_spanish.html" urls.py urlpatterns = [ re_path(r'^$', views.HomePageView.as_view(), name= 'home'), # Notice the URL has been named re_path(r'^about/$', views.AboutPageView.as_view(), name= 'about'), re_path(r'^chat/$', views.chat, name = 'chat'), re_path(r'^play/$', views.PlayPageView.as_view(), name = 'play'), re_path(r'^profile/$', views.ProfilePageView.as_view(), name = 'profile'), re_path(r'^scores/$', views.ScoresPageView.as_view(), name = 'scores'), re_path(r'^settings/$', views.SettingsPageView.as_view(), name = 'settings'), re_path(r'^practice_languages/$', views.Practice_languagesPageView.as_view(), name = 'practicelang'), re_path(r'^practicehtml/$', views.practicehtml, name = 'practicehtml'), re_path(r'^quiz_languages/$', views.Quiz_languages.as_view(), name = 'quiz_languages'), re_path(r'^quizhtml/$', views.quizhtml, name = 'quizhtml'), re_path(r'^practice_spanish/$', views.practice_spanish.as_view(), name = 'practice_spanish'), re_path(r'^quiz_spanish/$', views.quiz_spanish.as_view(), name = 'quiz_spanish'), path("chatrooms/<str:room_name>/", views.room, name="room"), path('admin/', admin.site.urls), re_path(r"^registration/$", views.registration, name = "registration"), re_path(r"^registration/register$", views.register, name = "register"), path("login_user", views.login_user, name="login_user"), path("index", views.home, name="home"), path("logout_user", views.logout_user, name="logout_user"), ] I am looking at practice_spanish and quiz_spanish. They are also named correctly as HTML files: my html files I tried to create 2 pages using the exact same way I created my others using the class-based views. I get an error this time when clicking on the buttons to take me to the 2 pages. -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
I have this APScheduler code: import atexit from apscheduler.schedulers.background import BackgroundScheduler from main.utils import run_employee_import scheduler = BackgroundScheduler() scheduler.add_job(run_employee_import, "interval", minutes=2) scheduler.start() # Shut down the scheduler when exiting the app atexit.register(lambda: scheduler.shutdown()) When I add this code to settings.py to run it when the app starts to run, it gives me the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error. -
How to use a Django (Python) Login Form?
I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login process canot work and the form is a simple static html form. I hope you can help me. HTML: <form class="windowlogscreen-content" method="POST" action={% url 'homepage' %}\> {% csrf_token %} <input type="text" placeholder="account" name="username"> <br> <input type="password" placeholder="password" name="password"> <br> <button style="margin: 20px;" type="submit">join</button> </div> </div> </form> views.py def loginuser(request): if request.method == "POST": username = request.POST\['accountName'\] password = request.POST\['accountPassword'\] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return views.homepage else: return redirect('start') else: return render(request, 'start', {})