Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to encrypt and decrypt access passwords in Django?
My Django application needs a table to store credentials of different users to access external databases that store their information. There are security and technical reasons not to use the same database that Django uses. But during storage, I would like to encrypt the passwords before inserting to the persistance, and later a way to decrypt them in order to make use of them. My first approach was to use make_password function, but I couldn't find a way to decrypt back the passwords. Right now I'm testing django signals with a pre_save script that encrypts the password using cryptographi.fernet algorithm. And later, this is decrypted inside the view execution. For encryption and decryption, I'm saving the key in settings file (loaded from environment). I would like to know if this is secure enough procedure to manage credentials to critical information of my users. Also if there is any way to get the password back when using make_password function. -
Django inbuilt Auth not logging me in despite successfully registering the user
i would like to login after registering a user that is saved using my customuser model that exends abstractuser. after registering the user, i redirect them to the login page. and when i try to login the user with the credentials that is just created, it will say "__ all __ Please enter a correct username and password. Note that both fields may be case-sensitive." when i print form.errors i am not sure why the backends is throwing this error, i have tried looking into the authenticationform that i extended as well as the save and create_user. just wondering too; is it better if i created a userprofile model instead of extending the default django user model? here is my models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password, **other_fields): print('in customusermanager create_user') if not email: raise ValueError(gettext_lazy('You must provide a valid email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, username, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser %s must be assigned to is_staff=True' % (username)) if other_fields.get('is_superuser') is not True: raise ValueError('Superuser %s must be assigned to … -
How do I set up python intepreter in VS code on Mac OS 13.4.1?
After I post the path of the project obtained by the command pipenv --venv into the command palette of vs code, it is supposed to create a new vs code settings file according to this tutorial https://www.youtube.com/watch?v=rHux0gMZ3Eg&t=3158s (timestamp 20 mins) however in my case, none of the changes are taking place. What could be the possible problem or solution for this? I tried creating a new directory which did not work. I even tried entering /bin/python3.11 as the path of the interpreter but it was unsuccessful. -
My css is no longer linking to my django template
Everything was working very fine,my css file was linking to my django template,all of a sudden everything stopped working. I already configured my settings.py,my URL'S.py,and used "{% load static %}" in my template and everything was okay but for some reason it just stopped at some point.Please can anyone please help with the solution I have tried to use a different browser but it still is not working -
how i doing deploy django app to vercel when i get this error
I've been stuck for a few days when I try to deploy my django app through the vercel. And vercel give the syntax error. Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-cc0ii6jl/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! ******************************************************************************** The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! parsed = self.parsers.get(option_name, lambda x: x)(value) running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). … -
ReactJS + django 400 bad request
I'm making website using django and react. I have already set up backend in django and tested it using postman, everything works fine but when I'm doing exact same thing using react i'm getting 400 error. Tried to do it like that: To avoid any other error I used static data in this example export default function MakePost(){ const [userID, setUserID] = useState(1); const [text, setText] = useState(''); const submit = async e => { e.preventDefault(); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({id: 1, text: 'some text'}) } fetch('http://localhost:8000/api/make-post/', requestOptions) .then(response => { console.log(response) if(response.ok){ return response.json(); } }); window.location.reload(); } -
Django How to download files from file system?
I'm fairly new to Django so any help will be much appreciated. I'm trying to make a link to a file path on a Windows server downloadable to the user after they click the file link. My app displays entries from a result of searching a ticket model. The results on the page include items like: Ticket number, description, status and a link to a flat file (that is stored on a Windows server network share drive; starting with \server.name\folder A\folder B\folder C\file to download.txt *Note \server.name, \folder A and \folder B are a constant \folder C (as well as the file to download are dynamic (they location and file name will change) users will NOT be uploading files. All files that are downloadable - are already saved to a Windows share. On the display page/template.html I can list all my values in a table (even a link the the file I'd like to download). However, when I hover over the link at the bottom of the browser I see file://server.name/folder A/folder B\folder C\file to download.txt. Yes, the last "slash" is a forward slash while all the others are back slashes (not sure why they are changing?) When I pass … -
I want to make Sales invoice، purchase invoice by django
I create models and forms then in template i repeat form to look like multi items but when i click save it save one of these item Can any one help me to solve Model = item.Name, price, quantity, expiry date, supplier name, item code, I want to write 25 item in on sales invoice Then save them all in one time -
import errors in pytest unable to run tests
I'm having a problem with my imports in my django project, I'm trying to run my first tests in pytest but I'm getting import errors: name = 'tasks', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) E ModuleNotFoundError: No module named 'tasks' /usr/local/lib/python3.11/importlib/__init__.py:126: ModuleNotFoundError ================================================================================= short test summary info ================================================================================= FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_existing_models_are_updated - ModuleNotFoundError: No module named 'tasks' FAILED core_apps/tracker/tests/test_tasks.py::FetchAndStoreVehicleModelsTest::test_new_models_are_created - ModuleNotFoundError: No module named 'tasks' this is my project diretory tree core_apps ├── __init__.py ├── tracker │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── services │ │ ├── coopart.py │ │ └── __init__.py │ ├── tasks.py │ ├── tests │ │ ├── __init__.py │ │ └── test_tasks.py … -
How to optimize django postgres search
I'm using postgres search on my Django project. And I must search by title, content and tag of article model. Couse of conetent could contain too many chars, search works too slow. For example, my db has 1000 articles and each article has 5000 chars there will be 5 million chars. So search will work slow. How can I optime it? # models.py class Article(models.Model): class Statuses(models.TextChoices): DRAFT = ( "draft", _("Draft"), ) PUBLISHED = "published", _("Published") BANNED = "banned", _("Banned") DELETED_ARTICLE = "deleted_article", _("Deleted Article") DELETED_AUTHOR = "deleted_author", _("Deleted Author") FOR_TEST = "for_test", _("For test") objects = ArticleQueryset.as_manager() title = models.CharField(verbose_name=_("title"), max_length=255) author = models.ForeignKey(User, related_name="articles", null=True, on_delete=models.SET_NULL) content = BleachField( verbose_name=_("content"), max_length=20000, validators=[MinLengthValidator(750)] ) status = models.CharField(max_length=15, choices=Statuses.choices, default=Statuses.DRAFT) banner = models.CharField(blank=True, max_length=255) created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True) modified_date = models.DateTimeField(auto_now=True, blank=True, null=True) deleted_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(default="", editable=False, max_length=255, null=False) read_time = models.IntegerField(default=0) liked_users = models.ManyToManyField(User, related_name="liked_articles", blank=True) view_count = models.IntegerField(default=0) total_users_viewed = models.IntegerField(default=0) # seconds total_users_engagement_duration = models.IntegerField(default=0) score = models.IntegerField(default=0, db_index=True) tags = TaggableManager() def __str__(self): return self.title # filters.py class ArticleFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="search_filter") def search_filter(self, queryset, _, value): search_vector = ( SearchVector( "title", weight="B", ) + SearchVector(StringAgg("tags__name", delimiter=" "), … -
Django DRF: Why is the field not populated by the user from the request
When sending a POST request to create a follow in the FollowViewSet view, there is a requirement to manually enter the user field. Why isn't the user field automatically populated and how can this be fixed? I suspect the issue is with the validator... views.py class FollowViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = FollowSerializer permission_classes = (IsAuthenticated,) filter_backends = (filters.SearchFilter,) search_fields = ('following__username',) def get_queryset(self): return self.request.user.follows_user.all() def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py class FollowSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field='username') following = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username' ) class Meta: fields = ('user', 'following') model = Follow validators = [ UniqueTogetherValidator( queryset=Follow.objects.all(), fields=['user', 'following'] ) ] def validate(self, data): user = self.context['request'].user if user.username == data['following']: raise serializers.ValidationError('Нельзя подписаться на себя!') return data models.py class Follow(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follows_user', verbose_name='Подписавшийся пользователь') following = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follows', blank=False, verbose_name='Пользователь, на которого подписаны') class Meta: verbose_name = 'Подписка' verbose_name_plural = 'Подписки' unique_together = ["user", "following"] def __str__(self): return f'{self.user.username} отслеживает {self.following.username}' With a GET request, all subscriptions should be displayed in the form: [ { "user": "string", "following": "string" } ] For a POST request with a request body like: { "following":"admin" } a Follow object should be created and output as a … -
How do I get around ModuleNotFoundError: No module named 'dot env
I am doing the official django tutorial polls app on part 5 which is about testing in django. As a part of the instructions I am supposed to go into my models.py file and run the python manage.py shell command to activate a shell terminal. From there I am supposed to run a series of commands to import things for my test. Link to material: https://docs.djangoproject.com/en/4.2/intro/tutorial05/ The commands I need to run are: >>> import datetime >>> from django.utils import timezone >>> from polls.models import Question >>> # create a Question instance with pub_date 30 days in the future >>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) >>> # was it published recently? >>> future_question.was_published_recently() True I run the import datetime, and from django.utils import timezone and there are no issues. Once I get to from polls.models import Question I am hit with an error message no modulenotfounderror" no module named dot env. I have tried looking at stack overflow articles and they suggested installing it via pip. So I exited my shell command and tried installing dotenv with pip. When I do so I get the following error message shown in the screenshot. I looked at this stack overflow article python … -
Implementing real time filtering/search with Django and React not working as expected
I'm trying to implement real time filtering/search with Django and React. But I'm not getting desired results? Please what did I do wrong? Here is my views.py file: class FilterFormView(generics.ListAPIView): serializer_class = JournalSerializer def get_queryset(self): qs = Journal.objects.all() title_contains_query = self.request.query_params.get("title_contains") if is_valid_query_param(title_contains_query): qs = qs.filter(title__icontains=title_contains_query) return qs The filtering Form in React looks like this: useEffect(() => { fetchJournals(); }, [title_contains]); const fetchJournals = async () => { setLoading(true); try { const res = await axios.get(myurl); setPost(res.data); setLoading(false); } catch (e) { console.log(e); } }; const handleChange = (e) => { settitle_contains({ ...title_contains, [e.target.name]: e.target.value, }); }; return ( <React.Fragment> <input onChange={handleChange} type="text" name="title_contains" id="title_contains" /> {post.map((jour) => { return <div>{jour.title}</div>; })} {loading && <div>Data is Loading</div>} </React.Fragment> ); This was how I set my url: const [title_contains, settitle_contains] = useState(""); const url = new URL("http://127.0.0.1:8000/api/?"); url.searchParams.set("title_contains", title_contains); I got this from the server console whenever I typed in the input field and no filtering occured in the frontend: [08/Jul/2023 19:40:38] "GET /api/?title_contains=%5Bobject+Object%5D HTTP/1.1" 200 2 But if url is set like this: const myurl = http://127.0.0.1:8000/api/?${title_contains}; Then I got this from the server console each time I type in the input field and no filtering occured in the … -
How to show more object information on forms in django
This is a follow up question to this question: How to pass user object to forms in Django Here is my form: class SellForm(forms.Form): symbol = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={ 'class': 'form-control', 'placeholder': 'Symbol', 'autofocus': 'autofocus', })) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(SellForm, self).__init__(*args, **kwargs) self.fields['symbol'].queryset = Holdings.objects.filter(student=self.request.user.student) This form is providing me with this dropdown: I have extra information in the model which is the purchase price of each share, is there a way to get this onto the form also? It would have to be non editable though as its the price that the share was purchased at. Here is the model that the form is getting the data from: class Holdings(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) symbol = models.CharField(max_length=10) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) class Meta: verbose_name_plural = "Holdings" ordering = ['symbol'] def __str__(self): return self.symbol I would very much appreciate any help if possible! Thank you! -
encoding with 'idna' codec failed (UnicodeError: label empty or too long)
Im using Django to host my backend, user inputs their email, I check if email exists if not I generate a token and send a verification email. However when I try and use the send_email() function I get the following error: encoding with 'idna' codec failed (UnicodeError: label empty or too long) Here is the section of code: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] UserModel = get_user_model() user, user_created = UserModel.objects.get_or_create(email=email) if user_created: token = default_token_generator.make_token(user) user_email, email_created = UserEmail.objects.get_or_create(email=email) if not email_created: user_email.token = token user_email.save() current_site = get_current_site(request) domain = current_site.domain.split(':')[0] print(domain) mail_subject = 'Activate your email' uid = urlsafe_base64_encode(force_bytes(user_email.pk)) message = render_to_string( 'verification_email.html', { 'user_email': user_email, 'domain': domain, 'uid': uid, 'token': token, }, ) send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False,) return redirect('email_sent') # Redirect to a success page else: # User with the same email already exists return render(request, 'email_exists.html') else: form = RegistrationForm() return render(request, 'register.html', {'form': form}) -
How can I use TokenAuthentication and HasAPIKey together in Django Rest Framework?
I have an APIView that works exactly how I need it to - I can make a request to it using a tool like Insomnia and/or I can make a request to it by clicking a button from the django website the API is part of. All work fine, however, I need to add security to it so that if a user makes a request from Insomnia, command line etc., they need to provide an API Key in the Authorization header, or if they click the button they need to be logged in and have a Token. See my settings.py file below: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', 'rest_framework.permissions.IsAuthenticated', ], } If I remove 'rest_framework_api_key.permissions.HasAPIKey' then the button works fine and a user is able to make a request to the API with it (as long as they pass the token checks etc of course). If I ONLY have 'rest_framework_api_key.permissions.HasAPIKey' in the settings then a user can make a request from Insomnia (or anywhere else) as long as they provide a valid API Key in the header, of course. (But then obviously the call from clicking the button doesn't work) However, I want to be able … -
NoReverseMatch: Reverse for 'view_director' with arguments '('',)' not found. 1 pattern(s) tried: ['crew/view_director/(?P<dslug>[-a-zA-Z0-9_]+)\\Z']
i made two apps called crew which contains the table Director and movie which contains the table Movie when i try to click this link, it shows the error given above. <a href="{% url 'crew:view_director' director.slug %}"> <img src="{{mov.director.photo.url}}" class="card-img-top rounded-0" alt="..."> </a> urls.py from django.urls import path from crew import views app_name='crew' urlpatterns = [ # function based path path('view_director/<slug:dslug>',views.view_director,name='view_director'), ] views.py from django.shortcuts import render from crew.models import * # Create your views here. def view_director(request,dslug): director=Director.objects.get(slug=dslug) return render(request,'director_detail.html',{'director':director}) models.py from django.db import models # from movie.models import Movie # Create your models here. class Director(models.Model): name=models.CharField(max_length=30,blank=True,null=True) photo=models.ImageField(upload_to='crew/director') slug=models.SlugField(max_length=50,unique=True,blank=True) # movies=models.ForeignKey(movie.Movie,on_delete=models.CASCADE,null=True) about=models.TextField(max_length=2000,blank=True) def __str__(self): return self.name also iam not getting the directors name and image from this code on the movie detail page <div class="card rounded-0" style="width: 14rem;"> <a href=""> <img src="{{mov.director.photo.url}}" class="card-img-top rounded-0" alt="..."> </a> <div class="card-body"> <h5 class="card-title">{{mov.director.name}}</h5> <p class="card-text">Director</p> </div> </div> How can i get the director detail page and display those details on the movie detail page, what am i doing wrong here ? -
django create object and many to many relationship in bulk
Hi I am trying to create multiple objects in bulk with a specific many to many field id specified. Looking at the documentation found this: >>> e = b.entry_set.create( ... headline="Hello", body_text="Hi", pub_date=datetime.date(2005, 1, 1) ... ) This works fine and creates the entry object as well as the many-to-many field relation as well. So modified this to handle bulk_creates: >>> e = b.entry_set.bulk_create( ... entry_objects ... ) This does create the entry objects however the many-to-many relation is not getting created in the database. Am I missing something here? -
Getting django.http.request when print for loop content
In django, I am trying to view google search result (2) for a keyword by using beautifulsoup. but when enter keyword I am getting result as "Source code for django.http.request https://docs.djangoproject.com/en/2.1/_modules/django/http/request/" views.py from django.shortcuts import render import requests # 👉️ Requests module from bs4 import BeautifulSoup # 👉️ BeautifulSoup module from django.http import HttpResponse def search(request): if request.method == "POST": url = f"https://www.google.com/search?q={request}" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } response = requests.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") results = [] search_results = soup.select("div.g") for result in search_results[:2]: # Limiting to the first 2 results title = result.select_one("h3").get_text() #description = result.select_one("div.IsZvec").get_text() link = result.select_one("a").get("href") results.append({"title": title, "link": link}) return render(request, "result.html", {"results":results}) return render(request, "result.html") Here is the template I am using as html template HTML Template <!DOCTYPE html> <html> <head> <title>Django FBV With Beautifulsoup</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <style> p { font-size: 20px } h1 { text-align: center; } </style> <body> <div class="container"> <h1 class="mt-5 mb-5">Get Title From Any Website</h1> <!-- Form --> <form method="POST" action="{% url 'results' %}"> {% csrf_token %} <div class="mt-4"> <div class="col"> <input type="text" name="keyword" class="form-control" placeholder="Enter keyword" rows="5" required="required"> </textarea> </div> … -
Using Postgres 'delete field' jsonb operator with Django ORM
I am using Postgres 14, Django 4.1, and Python 3. I have a JSONB field which contains a lot of data. To reduce bandwidth, I am reducing the amount of data selected by using the #- operator. This works, but now because of the way I queried it, the model no longer matches and my JSONField() doesn't parse. I would like to retain the model somehow, so the getters and setters are retained. Is there a way I can annotate this extra selection so that it matches or casts to my model? Here is my model: class MyModel(Model): class Meta: managed = True db_table = "MyModel_data" id = UUIDField(primary_key=True, default=uuid.uuid4) created_at = DateTimeField(auto_now_add=True, blank=True, null=False) _data = JSONField(db_column="data", blank=False, null=False, encoder=DjangoJSONEncoder) @property def data(self) -> Any: return cast_deep_floats(self._data) @data.setter def data(self, value: Any) -> None: self._data = value And here is my controller: search = MyModel.objects.filter(id=123).order_by('-created_at') excluded_data_points = ['incredibly_large_field', 'another_incredibly_large_field'] excluded_data_query = 'data #- ' + ' #- '.join(["'{%s}'" % f for f in excluded_data_points]) result = search.extra( select={ 'data': excluded_data_query } ).values('data').first() found = None try: found = json.loads(result['data']) except: # pylint: disable=bare-except pass I have tried a ton of variations of .annotate(data=Cast('data', .....) but I keep running into … -
I got a problem runing a django project and got this error DataFrame.drop() takes from 1 to 2 positional arguments but 3 were given
def forecast(request): global graph if request.user.is_authenticated: pass else: return redirect('/login') if request.method == "POST": stock_name = request.POST.get('stock_name') pred_df, df = calPred(stock_name) graph = None plot1(df, pred_df, "Stock Price Prediction of "+str(stock_name), 'Date', 'Price', 'blue') print(pred_df.reset_index().columns) pred_df = pred_df.reset_index() pred_df['index'] = pred_df['index'].astype(str) json_records = pred_df.to_json(orient='records') data = json.loads(json_records) df = df.reset_index() df['Date'] = df['Date'].astype(str) df['Open'] = df['Open'].astype(float) df = df.iloc[::-1] json_records2 = df.head(120).to_json(orient='records') data2 = json.loads(json_records2) context = { 'chart': graph, 'd' : data, 'd2' : data2, 'visible': "visible", } #print('GG :: ',graph) return render(request, 'forecast.html', context) context = {'visible': "invisible"} return render(request, 'forecast.html',context) Internal Server Error: /forecast/ Traceback (most recent call last): File "C:\Users\ngeti\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\OneDrive\Desktop\c\Stock_price_Prediction-main working\stock\views.py", line 162, in forecast pred_df, df = calPred(stock_name) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\ngeti\OneDrive\Desktop\c\Stock_price_Prediction-main working\stock\views.py", line 201, in calPred x = np.array(df.drop(['Prediction'], 1)) ^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: DataFrame.drop() takes from 1 to 2 positional arguments but 3 were givenDD -
NoReverseMatch at / Reverse for 'category_posts' with arguments '('',)' not found
im currently working on website, which can show posts written by people. For this posts i have a database. On the main i need to show all the posts which i have in database. There should be some link which will go to page with posts information. I have trouble with all pages - there is error NoReverseMatch at / Reverse for 'category_posts' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category_slug>[-a-zA-Z0-9_]+)/\\Z']. When i open my website locally it shows that the error in <a class="text-muted" href="{% url 'blog:category_posts' post.category.slug %}"> There is the code: views.py def category_posts(request, category_slug): template = 'blog/category.html' posts = Post.objects.select_related( 'author', 'category', 'location', ).filter( category__slug=category_slug, is_published=True, pub_date__lte=now()) category = get_object_or_404( Category.objects.select_related('title', 'description', 'slug') .filter(is_published=True), slug=category_slug ) context = {'posts': posts, 'category': category} return render(request, template, context) urls.py from blog import views from django.urls import path app_name = 'blog' urlpatterns = [ path('', views.index, name='index'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('category/<slug:category_slug>/', views.category_posts, name='category_posts'), ] category_link.html <a class="text-muted" href="{% url 'blog:category_posts' post.category.slug %}"> «{{ post.category.title }}» </a> -
request.session.clear() vs request.session.flush() in Django
I tried both request.session.clear() and request.session.flush() and they deleted all session data and logged a user out. Actually, there is the explanation for request.session.flush() as shown below while there isn't for request.session.clear(): Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it). My questions: What is the difference between request.session.clear() and request.session.flush()? Which should I use basically? -
Configuration of Django-admin fields
I’m trying to adjust the following logic: there is field 1 - BooleanField and field 2 - CharField, if field 1 = True, then field 2 is open for enter information. Otherwise the information in field 2 is erased and the field is closed for input. Now it is realized only at the level of the form of product creation through JS. If you save the product and open it for editing, the field state is reset. To save the status it is written as follows: Admin.py class SmartPhoneAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not kwargs.get('instance').sd: self.fields['sd_value'].widget.attrs.update({ 'readonly': True, 'style': 'background: #050505;' }) def clean(self): if not self.cleaned_data['sd']: self.cleaned_data['sd_value'] = None return self.cleaned_data The problem is that the expression kwargs.get('instance') returns None and I get an error. attributeerror: 'nonetype' object has no attribute 'sd' and i don't understand why instance = None. Full code: Admin.py class SmartPhoneAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not kwargs.get('instance').sd: self.fields['sd_value'].widget.attrs.update({ 'readonly': True, 'style': 'background: #050505;' }) def clean(self): if not self.cleaned_data['sd']: self.cleaned_data['sd_value'] = None return self.cleaned_data class SmartPhoneAdmin(admin.ModelAdmin): change_form_template = 'admin.html' form = SmartPhoneAdminForm prepopulated_fields = {'slug':('title',)} def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'category': return ModelChoiceField(Category.objects.filter(slug = 'smartphone')) return … -
pipenv failed to lock when trying to install mysqlclient in a django project
I tried running pipenv install mysqlclient in terminal here is the error message: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Adding mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (a01621) out of date, updating to (b35795)... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ⠹ Locking... ERROR:pip.subprocessor:[present-rich] Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 811, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 759, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/resolver.py", line 738, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 1165, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 964, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 701, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run …