Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set refresh token expire of drf social oauth2?
How can we set refresh token expire of drf social oauth2. I try to use this but not work(Work only access token). OAUTH2_PROVIDER = { 'REFRESH_TOKEN_EXPIRE_SECONDS': 1, #set to 1 second for test 'ROTATE_REFRESH_TOKEN': false, } Anyone can help? -
webRTC audio - Don't know how to resume streaming after closing/stoping it
I was trying webRTC for a chatbot with voice prompts. I was successful on incorporating the voice prompts to the chat, but i have a problem. I noticed the mediaRecorder.stop doesn't stop the streaming, so the red circle in the window will not dissapear. I want it to only be streaming when the user is recording the message. What i tried: I searched other solutions and found that this line will successfully end the streaming: stream.getTracks().forEach( track => track.stop() ); The problem is, I don't know how to resume the streaming after that, the record button turns unresponsive. This is my entire code, sorry for not providing a more compact one, i'm not too keen with javascript to leave things behind: let mediaRecorder; let recordedChunks = []; let isRecording = false; // Track the recording state // Function to start recording function startRecording() { if (mediaRecorder && mediaRecorder.state === 'inactive') { mediaRecorder.start(); isRecording = true; } } // Function to stop recording function stopRecording() { if (mediaRecorder && mediaRecorder.state === 'recording') { mediaRecorder.stop(); isRecording = false; } } // Function to initialize the MediaRecorder function initializeMediaRecorder() { if (!mediaRecorder) { // Initialize the MediaRecorder with audio constraints navigator.mediaDevices .getUserMedia({ audio: … -
Getting this error while using Django Tenant with DRF Exception: Can't create tenant outside the public schema. Current schema is ... while using DRF
So I am using django tenant with django rest framework. I have two created apps users and students. For users I was able to setup the model, serializer and viewset and create users using the viewset with no issues. Mirrored most of the logic for creating users in students but been having issues creating a student using the API. Keep getting the error Exception: Can't create tenant outside the public schema. Current schema is concord. I have tried finding a similar issue on stack overflow but not seen anything similar. Would appreciate any help. Find relevant snippets below # MIDDLEWARE # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#middleware MIDDLEWARE = [ "django_tenants.middleware.main.TenantMainMiddleware", "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] # ------------------------------------------------------------------------------ SHARED_APPS = ( "django_tenants", # mandatory "dew_school_management_system.school", "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.staticfiles", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", "django.forms", "django_filters", "dew_school_management_system.users", "crispy_forms", "crispy_bootstrap5", "allauth", "allauth.account", "allauth.socialaccount", "django_celery_beat", "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "corsheaders", "drf_spectacular", ) TENANT_APPS = ( "django.contrib.auth", "django.contrib.sessions", "dew_school_management_system.users", "dew_school_management_system.students", # Your stuff: custom apps go here ) # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] # TENANT CONFIGURATION TENANT_MODEL = "school.School" TENANT_DOMAIN_MODEL = "school.SchoolDomain" I … -
AttributeError: 'Response' object has no attribute 'streaming' in packages\django\middleware\common.py
Using requests we are unable to get a 200 success code due to either a bug in the common file or a wrong way of sending the request or receiving the response. Here are the technical details: Calling script import requests try: post_data = {'langs': langs, 'langs_json': []} # filling post_data.. response = requests.post(api_call_url, json=post_data, verify=False) return response except Exception as e: return JsonResponse({}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Serving script @csrf_exempt def api_end_point(request): try: data = json.loads(request.body.decode('utf-8-sig')) with open(os.path.join(r'assets\i18n', f'fr.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][0], f) with open(os.path.join(r'assets\i18n', f'en.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][1], f) # All works above.. the issue has something to do with the response itself.. response = JsonResponse(dict(status=True), safe=False, status=status.HTTP_200_OK) response.status_code = 200 # trying to solve.. return response except Exception as e: response = JsonResponse(dict(status=False), safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) response.status_code = 500 # trying to solve.. return response Error msg File "C:\Users\***\Desktop\****\*****\*****\venv\lib\site-packages\django\middleware\common.py", line 112, in process_response if not response.streaming and not response.has_header('Content-Length'): AttributeError: 'Response' object has no attribute 'streaming' common.py snippet def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then … -
Byte range requests in Django REST + nginx (dokku)
In my Django application, I have a Video model with a file FileField that represents a user-uploaded video. I serve these files via a Django REST API view that looks like this: class VideoViewSet(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = VideoSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() file = instance.file response = FileResponse( file, as_attachment=True, ) response["Content-Disposition"] = 'attachment; filename="video.mp4"' response["Accept-Ranges"] = "bytes" return response the frontend accesses the video like this: <video playsinline controls> <source type="video/webm" :src="videoUrl"/> <p> Videos are unsupported in your browser </p> </video> The application is deployed using dokku, which has gunicorn and nginx sit in front of Django. The problem is: in production, when the video player is opened, I am unable to seek. The video just proceeds from timestamp 00:00 all the way to the end, even if I drag the video timeline thumb to other positions. I learned that has to do with byte range requests, and not supporting them is the cause of not being able to seek while the video is playing. Adding response["Accept-Ranges"] = "bytes" in my viewset makes it work locally, but when I push to production the problem is still there. What can I do to solve … -
'TranslateCategory' object is not iterable in DRF
I use Django Rest Framework and run my code with gunicorn. And i got this error 'TranslateCategory' object is not iterable. Traceback: Request Method: GET Request URL: http://oralbekov.dias19.fvds.ru/api/translate/categories/1/ Django Version: 3.2.16 Python Version: 3.8.10 Installed Applications: ['jazzmin', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'questions.apps.QuestionsConfig', 'calendartodo.apps.CalendartodoConfig', 'rites.apps.RitesConfig', 'map.apps.MapConfig', 'news.apps.NewsConfig', 'translate.apps.TranslateConfig', 'info.apps.InfoConfig', 'reportederrors.apps.ReportederrorsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/var/www/hajjum/translate/views.py", line 30, in categories_id return Response(serializer.data ,status=status.HTTP_200_OK) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 768, in data ret = super().data File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 686, in to_representation return [ Exception Type: TypeError at /api/translate/categories/1/ Exception Value: 'TranslateCategory' object is not iterable Here … -
How to make dynamic menu & navbar from database in Django
I am developing a digital marketing agency website and there are services that this agency provides. There are 4 categories and each category has its own services. In the navbar there is a dropdown menu, when you hover "Our Services" there is a list of categories and services that below the categories. So I want to make this dynamic. The categories and the services that below the categories should come from database. But with my codes and tries; dropdown menu shows nothing. Here is my codes: Models.py from django.db import models from ckeditor.fields import RichTextField from django_resized import ResizedImageField class Category(models.Model): name = models.CharField(max_length=100, blank=True) slug = models.SlugField(max_length=100, unique=True, null=True) def __str__(self): return self.name class Service(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True,) available = models.BooleanField(default=True) slug = models.SlugField(max_length=100, unique=True, null=True) def __str__(self): return self.name views.py def navbar_services(request): categories = Category.objects.all() services = Service.objects.filter(category=categories) context = { 'categories': categories, 'services': services } return render(request, 'partials/_navbar.html', context) partials/_navbar.html <li class="menu-item main-nav-on menu-item-has-children"> <a href="#"><span class="rolling-text">Our Services</span></a> <ul class="mega-menu-01 sub-menu elements" style="display: block;"> {% for cat in categories %} <li class="single-mega"> <a class="tag" href="#">{{cat.name}}</a> <ul class="main-wrapper" style="display: block;"> {% for item in cat.service_set.all %} <li class="menu-item"><a class="menu-link" href="banner.html">{{ item.name }}</a></li> {% … -
How to properly select tags in jqXHR returned by jQuery $.post
I am building a barebones webapp in django with jQuery. I am running into an issue properly getting at HTML elements that are returned in jqXHR from a $.post call. $.post is called from a js function that bundles up some timestamp data and hits a django endpoint, which in return serves an HTML file that contains a couple <tbody> tags and a <div>, which are inserted into the main page by jQuery .replaceWith calls. The tangle I'm running into is that jQuery is able to access and handle the <tbody> elements just fine, but cannot locate the <div>. Code below has been synopsized a bit to save space. js function that generates the post call and handles insertion to main page funciton getDbUpdate(){ let _WaitTimes = JSON.stringify(compileWaitTimes()); $.post("{% url 'checkForDbUpdate' %}", {_WaitTimes, csrfmiddlewaretoken: '{{ csrf_token }}'}, function(data, status){ if (status!='nocontent'){ const queueTableHTML = $(data).filter("#queueTableBody").html(); //works const archiveTableHTML = $(data).filter("#archiveTableBody").html(); //works const targetDivElet = $(data).filter("#targetDivElet").html(); //returns nothing $('#queueTable > tbody').replaceWith(queueTableHTML); $('#archiveTable > tbody').replaceWith(archiveTableHTML); $('#targetDivElet').replaceWith(targetDivElet) }; ); }; django endpoint from views.py def checkForDbUpdate(request): if request.method == "POST": # --> do some database operations # return http 204 if nothing has changed between polls if ids_from_request==ids_from_model: response = HttpResponse() response.status_code=204 return … -
How do I set up a Django user for use in a Selenium test case with the setUp method?
I am working to create Selenium unit tests for my code. I have a simple login form: <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="f00b4r"> <div id="div_id_username" class="form-group"> <label for="id_username" class="requiredField">Callsign <spanclass="asteriskField">*</span> </label> <div> <input type="text" name="username" autofocus="" maxlength="150" class="textinput textInput form-control" required="" id="id_username"> </div> </div> <div id="div_id_password" class="form-group"> <label for="id_password" class="requiredField">Password <span class="asteriskField">*</span> </label> <div> <input type="password" name="password" autocomplete="current-password" class="textinput textInput form-control" required="" id="id_password"> </div> </div> <button class="btn btn-primary" type="submit">Login</button> </form> And this is the test case: class TestLoginFormFirefox(LiveServerTestCase): def setUp(self): self.driver = webdriver.Firefox() self.good_user = User.objects.create_user(username="unittest", password="this_is_unit") def tearDown(self): self.driver.close() def test_index_login_success(self): """ When a user successfully logs in, a link to their profile should appear in the navbar """ self.driver.get('http://127.0.0.1:8000/login') username_field = self.driver.find_element(by=By.ID, value='id_username') password_field = self.driver.find_element(by=By.ID, value='id_password') username_field.send_keys('unittest') password_field.send_keys("this_is_unit") login_button = self.driver.find_element(by=By.CLASS_NAME, value="btn-primary") login_button.send_keys(Keys.RETURN) # needs time to render sleep(3) id_profile_link = self.driver.find_element(by=By.ID, value='id_profile_link').text assert id_profile_link == 'unittest' The test is simple: if the user specified in the unittest setUp method is able to successfully log in, assert that the user's username is a part of a link in the next page. The rub here is that the setUp method creates the user object, but the login fails. This persisted until I made a user in the project's … -
How to update Docker interpreter when requirements.txt is updated
i add some library to requirement.txt but Docker interpreter in pycharm do not update and when i install some library in dockr container i get this error some error and warning. this is warning = WARNING: The directory '/home/shop/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag. and this is error = ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/py/lib/python3.11/site-packages/urllib3' Check the permissions. you can see my docker file. FROM hemanhp/djbase:4.2.4 COPY ./requirements /requirements COPY ./scripts /scripts COPY ./src /src WORKDIR src EXPOSE 8000 RUN /py/bin/pip install -r /requirements/development.txt RUN chmod -R +x /scripts && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ adduser --disabled-password --no-create-home shop && \ chown -R shop:shop /vol && \ chmod -R 755 /vol ENV PATH="/scripts:/py/bin:$PATH" USER shop CMD ["run.sh"] -
Using Fetch in REACT for PUT/PATCH doesn't work for me
Hello in my React App I use this specific comportement to handle modification (status change actived/deactived) const handleActifEspece = (index, statutActif) => { let especeAActiver = especes.find(espece => espece.id === index) especeAActiver.actif = statutActif console.log(JSON.stringify(especeAActiver)) fetch(`http://localhost:8000/api/especes/${index}`, { method: 'PUT', headers: { 'Content-type': 'application/json; charset=UTF-8',}, body: JSON.stringify(especeAActiver) }) .then(response => response.json()) .then(data => { snackBar.openSnackbar("Espèce modifiée !") setSnackMode('success'); setEspeces([...especes, data]) }) .catch(error => { console.error("Erreur pendant l'activation de l'espèce", error); snackBar.openSnackbar("Espèce non modifiée !") setSnackMode('error'); }) }; When I click on button in log I've got specific data : The JSON Stringigy of ma var is : {"id":40,"nom":"Test 6","gaf":false,"actif":true,"instance":{"id":1}} I've got ERROR 500 I use the DjangoRestFramework to handle API When I copy past the dat the url and got to PUT here is the error in Swagger : { "instance": [ "Incorrect type. Expected pk value, received dict." ] } It's working well for POST (add) and DELETE but for PUT or PATCH it doesn't :( Please help ;) -
Why did my API get duplicated in swagger?
I created a couple of new APIs to request and calculate scores from a giver user, one is supposed to be a GET (Get Score), and the other one is just a PATCH (Calc Score), for whatever reason the later one got duped into an additional GET that I never made nor did I give it a URL, what did I do wrong? Can I fix it or is it an inherent property of PATCH methods to create an auxiliary GET? As seen here -
How to comunicate database and web app which are in two different serevers?
I have a mysql database and a django web app but they are in two separated servers (two laptops) and o I want to know how can I comunicate them. Does anyone have a manual that i can read or watch? I'm expecting for a manual/guide to lear how to achieve it <- sorry for repated that. -
Grab last url parameter in referer
Is there a way without actually parsing the data wit a custom function to get the last piece of a url in django? so if the url looks like this http://192.168.1.100/test/article/1 And i just want to be able to grab the 1 without actually having query paramaters in the url. -
How to assign user for Celery tasks?
I'm planning a project that will make use of Celery tasks that will perform CRUD operations on my models. In addition, I have Signals in place that will listen for those CRUD operations and I want to specifically log that it was a Celery task (or a Celery task user) performing the operation. So would I accomplish assigning a User to my Celery workers so that whenever they interact with my models I can track that? @receiver(pre_save, sender=Location) def location_pre_save(sender, instance, update_fields=None, **kwargs): try: old_location = Location.objects.get(id=instance.id) # Log Celery user has updated this Location except Location.DoesNotExist: # Log Celery user has created this Location -
Relationship Type Between Comments and an App
I'm new to setting up database schemas and am working a problem where I have multiple models that should contain a comments section. I'm using Django with SQLite for reference. For example there are Projects which are made up of Tasks. Each Project and Task should have a comments section. Projects can contain many Tasks, but one task will only point to one Project. I have one model for Comments that will ever only point to one Project or one Task, but Projects and Tasks will have multiple Comments. I think what I want is a Many to one relationship on the Comments model, but then I would need multiple FK fields depending on where the comment is attached (Project or Task). My full app will have 8-10 locations where we'd want to have comments. Thanks in advance! -
How to avoid Django to change field on model migration when using makemigrations?
I need to avoid python manage.py makemigrations to alter the uniqueness of a field. The reason behind it is that if I leave the unique=True on the model the function bulk_create with update_conflicts generates the following error: django.db.utils.ProgrammingError: there is no unique or exclusion constraint matching the ON CONFLICT specification This error does not occurs if I migrate with unique=True then I remove it when running the app. It may be a bug on the update_conflicts implementation as it's recent. Here is the function to bulk_create: MyModel.objects.bulk_create( vendors, update_conflicts=True, unique_fields=["my_field"], update_fields=["other_field", "another_field"], ) Here is the initial model creation: # 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="MyModel", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("my_field", models.CharField(db_index=True, max_length=50, unique=True)), ... ], ), ] Here is what I want to avoid when rerunning makemigrations as I want to keep field uniqueness. # 0002_alter_my_table_my_field.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("my_database", "0001_initial"), ] operations = [ migrations.AlterField( model_name="my_model", name="my_field", field=models.CharField(db_index=True, max_length=50), # I need this to continue unique ), ] `` -
Django admin drop down menu dependent won't load
First, I know there are other post on topic but until now none worked for me hence here I am kindly asking your help. The task is simple: in Django Admin I have a form with a drop-down menu whose select must filter and fill-in another drop-down menu. First I tried to simply add a jQuery to my form to get the changes on field select. The .js is correctly loaded together with other Javascripts but simply nothing happen when I made a selection on the parent drop-down. Second I tried to add the widget on form declaration. Same result as above. Following is my last attempt, result as above: Models.py class Utenti(models.Model): nome = models.CharField(max_length = 188) cognome = models.CharField(max_length = 188) dataNascita = models.DateField(max_length = 8, verbose_name = "Data di nascita") genere = models.CharField(max_length = 19, choices = generi, null = True, blank = True, verbose_name = "Genere") provincia = models.ForeignKey(Provincia, on_delete = models.SET_NULL, null = True) citta = models.ForeignKey(Comune, on_delete = models.SET_NULL, null = True, verbose_name = "Citta'") cf = models.CharField(max_length = 16, validators = [ validate_codice_fiscale ]) class Meta: verbose_name = "Utente" verbose_name_plural = "Utenti" def __str__(self): return str(self.nome) + " " + str(self.cognome) Admin.py class … -
Reverse for 'category_2' with arguments '('',)' not found
I want whenever I click on the category, I can see the available categories and by clicking on each one I can display the products of that category and again by clicking on the product name, I can see the page of that product. Here, clicking on the category in the first step will display this error. what's the reason in views.py: def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) comments = Comment.objects.filter(product=product) offers = PriceOffer.objects.filter(product=product).order_by('-offer_price') off_list = [float(product.first_bid)] maximum = float(product.first_bid) if request.method == 'POST': #comment #offer context = { 'product': product, 'comments': comments, 'offers': offers, 'off' : off } return render(request, 'auctions/product_detail.html', context) def category(request): categories = Category.objects.all() return render(request, 'auctions/category.html', {'categories': categories}) def category_2(request,cat_id): category = Category.objects.get(id=cat_id) products = Product.objects.filter(category=category) return render(request, 'auctions/product_detail.html', {'category': category, 'products': products}) urls.py: path("product_detail/<int:product_id>/", views.product_detail, name="product_detail"), path("category", views.category, name="category"), path("category_2/<int:cat_id>/", views.category_2, name="category_2"), category.html: {% extends "auctions/layout.html" %} {% block body %} <h3><a href="{% url 'category_2' cat_id %}">{{ category.name }}</a></h3> {% endblock %} product_detail.html(Only the relevant part): <h2>{{ category.name }}</h2> {% for product in products %} <h3>{{ product.name }}</h3> {% endfor %} layout.html(Displays the linked category at the top of the page): <li class="nav-item"> <a class="nav-link" href="{% url 'category' %}">Category</a> </li> error: Request Method: … -
Data is not getting into database from Django form
I press 'submit' button, there is 'post' request in the terminal, but there is no new model in database. forms.py class PinCreationForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={ 'class':'create-pin-file-input' })) name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Богатый мужчина' })) description = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Мужик стоит дрочит' })) tags = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Спорт, Машина, Огород' })) class Meta: model = PinModel fields = ('image', 'name', 'description', 'tags') models.py class PinModel(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) tags = models.TextField() image = models.ImageField(upload_to='pin_images') user = models.ForeignKey(to=User, on_delete=models.CASCADE) views.py class CreatePinView(CreateView): model = PinModel form_class = PinCreationForm template_name = 'pinapp/create-pin.html' success_url = reverse_lazy('users:login') html section class="create-pin-section"> <div class="create-pin-div"> <h2>Create Pin</h2> <form action="{% url 'create-pin' %}" class="create-pin-form" method="post"> {% csrf_token %} <label for="{{ form.image.id_for_label }}">Choose Pic</label> {{ form.image }} <label for="{{ form.name.id_for_label }}">Choose da name</label> {{ form.name }} <label for="{{ form.description.id_for_label }}">Choose da description</label> {{ form.description }} <label for="{{ form.tags.id_for_label }}">Choose da tags</label> {{ form.tags }} <button type="submit">Create</button> </form> </div> </section> i want to explain, that i want is for the 'user' field to be filled in with the user who submitted the form i tried everything that i found, no results. -
Trouble install mysqlclient in Cpanel
Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb # Options for building extention module: extra_compile_args: ['-I/usr/include/mysql', '-std=c99'] extra_link_args: ['-lmariadb', '-pthread', '-lz', '-ldl', '-lm', '-lpthread', '-lssl', '-lcrypto'] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/times.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/release.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/init.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-39/MySQLdb creating build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/init.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants running egg_info writing src/mysqlclient.egg-info/PKG-INFO writing dependency_links to src/mysqlclient.egg-info/dependency_links.txt writing top-level names to src/mysqlclient.egg-info/top_level.txt reading manifest file 'src/mysqlclient.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE' writing manifest … -
Django admin login not showing OTP Device
I tried adding the otp_totp plugin. and pip install the requirements but still not getting anywhere. I have added different creating a models.py file and an admin.py file still not helping. This is my settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] The urls.py file from django.contrib import admin from django.urls import path from django_otp.admin import OTPAdminSite from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite urlpatterns = [ path('admin/', admin.site.urls), ] [enter image description here](https://i.stack.imgur.com/QwFQ6.png) -
Add a condition to query list of a function in Python
I have an eCommerce website with Django, I want to put a condition with if statement to my payment function that only if product sold status is false proceed to payment and if not output a message to user. I cannot workout a way to approach this. any help would be appreciated here is my payment function : def acc_go_to_gateway_view(request): cart_items = AccountCart.objects.filter(user=request.user) print (cart_items) total_price = 0 if cart_items: for item in cart_items: total_price += (item.product.price) * item.quantity amount = total_price user_mobile_number = '' factory = bankfactories.BankFactory() try: bank = factory.auto_create() bank.set_request(request) bank.set_amount(amount) bank.set_client_callback_url('/acc-callback-gateway') bank.set_mobile_number(user_mobile_number) # اختیاری bank_record = bank.ready() return bank.redirect_gateway() except AZBankGatewaysException as e: logging.critical(e) raise e and this is my product model sold status is like this : class Product(models.Model): . . . . sold = models.BooleanField(default=False) and the Cart model that the bank function conntects to is : class Cart(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(AccountProduct, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.product.name since the payment function works with my cart model , and in my cart model the product model connects via a foreign key i couldnt use filter() modifier and i cant workout how to do this -
python program use case for the interview [closed]
You are given words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. Note: Each input line ends with a "\n" character. Constraints: The sum of the lengths of all the words do not exceed All the words are composed of lowercase English letters only. Input Format The first line contains the integer, . The next lines each contain a word. Output Format Output lines. On the first line, output the number of distinct words from the input. On the second line, output the number of occurrences for each distinct word according to their appearance in the input. Sample Input 4 bcdef abcdefg bcde bcdef Sample Output 3 2 1 1 Explanation There are distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output. -
Getting Users current Page url in djangorestframework
How can I get the url a user is making their request "from" in Django Rest Framework? Currently using const current_url = window.location.href const api_key = "API_KEY" fetch(`http://127.0.0.1:8000/posts/api/${api_key}?url=${current_url}) But I feel this method isn't secure enough as it can be altered from the front end, and a different URL can be hardcoded there. So, I need to get the user's current url from the Backend.