Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with .only() method, passing to Pagination / Serialization --- all fields are getting returned instead of the ones specified in only()
I am trying load some data into datatables. I am trying to specify columns in the model.objects query by using .only() --- at first glance at the resulting QuerySet, it does in fact look like the mySQL query is only asking for those columns. However, When I try to pass the QuerySet into Paginator, and/or a Serializer, the result has ALL columns in it. I cannot use .values_list() because that does not return the nested objects that I need to have serialized as part of my specific column ask. I am not sure what is happening to my .only() db_result_object = model.objects.prefetch_related().filter(qs).order_by(asc+sort_by).only(*columns_to_return) paginated_results = Paginator(db_result_object,results_per_page) serialized_results = serializer(paginated_results.object_list,many=True) paginated_results.object_list = serialized_results.data return paginated_results -
Why are my items not showing in my cart? Django
Can someone tell me why my products are not showing up on my cart? They are being added to the database but somehow not showing up on my page. I will attach some screenshots of my project: These are the important views: enter image description here This is the form used to add the products to cart: enter image description here And this is the cart.html, where nothing shows up: enter image description here This shows up once I open the cart on the browser: enter image description here -
TypeError: test_load_category_from_OFF() missing 1 required positional argument: 'monkeypatch'
def test_load_category_from_OFF(self, monkeypatch): def mockreturn(): test_category_loaded = [ {'category_name': 'Aliments et boissons à base de végétaux', 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-et-boissons-a-base-de-vegetaux'}, {'category_name': "Aliments d'origine végétale", 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-d-origine-vegetale'}, {'category_name': 'Snacks', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks'}, {'category_name': 'Viandes', 'category_url': 'https://fr.openfoodfacts.org/categorie/viandes'}, {'category_name': 'Snacks sucrés', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks-sucres'} ] return test_category_loaded monkeypatch.setattr(category_importer, 'load_category_from_OFF', mockreturn) expected_results = [{'category_name': 'Aliments et boissons à base de végétaux', 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-et-boissons-a-base-de-vegetaux'}, {'category_name': "Aliments d'origine végétale", 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-d-origine-vegetale'}, {'category_name': 'Snacks', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks'}, {'category_name': 'Viandes', 'category_url': 'https://fr.openfoodfacts.org/categorie/viandes'}, {'category_name': 'Snacks sucrés', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks-sucres'} ] category_loaded = self.category_importer.load_category_from_OFF() category_fetched = self.category_importer.fetch_category(category_loaded, 5) assert category_fetched == expected_results I don't understand where is my error. When I run the test, I have the message below : E TypeError: test_load_category_from_OFF() missing 1 required positional argument: 'monkeypatch' But I don't know where I'm wrong. Please help ^^' this my file of category : """Internal imports""" from requests import get from purbeurre_website.models import Category class CategoryImporter: """ Import category of products from the API OpenFoodFacts(OFF) and insert it in the database. """ def __init__(self): self.category_table = Category.objects.all() @staticmethod def load_category_from_OFF(): """ Loads the categories datas from the URL address in OFF. """ categories_url = "https://fr.openfoodfacts.org/categories&json=1" request = get(categories_url) # To get the json format categories_url_json = request.json() return categories_url_json @staticmethod def fetch_category(categories_url_json, nb_category): # We … -
DRF TimeZoneField: not JSON serializable error
I have django model: from django.db import models from timezone_field import TimeZoneField class Client(models.Model): time_zone = TimeZoneField(choices_display='WITH_GMT_OFFSET') And APIView for this model: class ClientAPIView(APIView): def get(self, request: Request, pk: int, format=None) -> Response: client = get_object_or_404(Client, pk=pk) client_serializer = ClientListSerializer(client) return Response(client_serializer.data) I get an error from GET request: TypeError: Object of type ZoneInfo is not JSON serializable Serializer code: class ClientListSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ('id', 'time_zone') How fix code of Model, Serializer or View (I don't know what exactly) so that instead of ZoneInfo there is just a string. UPDATE: if change serializer: class ClientListSerializer(serializers.ModelSerializer): time_zone = serializers.CharField(max_length=256) GET request will be work, but POST request give me error, if send invalid string for time zone. For example {"time_zone": "invalid string"} Result: django.core.exceptions.ValidationError: ["Invalid timezone 'invalid string'"] My POST method code: def post(self, request: Request, format=None) -> Response: client_serializer = ClientSerializer(data=request.data) if not client_serializer.is_valid(): return Response(client_serializer.errors, status=status.HTTP_400_BAD_REQUEST) client_serializer.save() return Response('client was created successfully', status=status.HTTP_201_CREATED) SOLVED Maybe this is not the best solution, but now requests work correctly after modify serializer: import pytz from rest_framework import serializers class ClientSerializer(serializers.ModelSerializer): time_zone = serializers.ChoiceField(choices=pytz.all_timezones) class Meta: model = Client fields = ('id', 'time_zone') If you know better solution, … -
Stripe Checkout with django-stripe: how pass fees on to customers (surcharging)?
I am using django-stripe to generate Stripe Checkouts. I would like to pass the Stripe fees on to my customers ("surcharging"). I found a help article from stripe regarding this. It says in general how to calculate the fees to put on top of the price of the product. The problem is, that different payment methods have different fees. And when creating the Checkout, I must calculate the final price (including the fees I want to pass on) before I know what payment method the customer will select (and therefore what fees the customer will have to pay). So I don't know the fees when I must put them on top of the price the user has to pay in the Checkout. Is there a way out of this dilemma? -
Use Django Model to find 1 record per hour, and the most recent one from another timestamp
Django 3.2.9 db: (PostgreSQL) 14.0 Model class InventoryForecast(models.Model): count = models.IntegerField() forecast_for = models.DateTimeField(null=False) forecasted_at = models.DateTimeField(null=False) Data id count forecast_for forecasted_at 8 40910 2022-10-10 11:00 2022-09-04 12:00 9 40909 2022-10-10 11:00 2022-09-05 12:00 10 50202 2022-10-10 11:00 2022-09-06 12:00 (most recent forecast) 11 50301 2022-10-10 12:00 2022-09-04 12:00 12 50200 2022-10-10 12:00 2022-09-05 12:00 13 50309 2022-10-10 12:00 2022-09-06 12:00 (most recent forecast) How would I use Django Model to find 1 record per forecast_for hour, and the most recent one for the forecasted_at value? So in this example, 2 records. Desired results id count forecast_for forecasted_at 10 50202 2022-10-10 11:00 2022-09-06 12:00 13 50309 2022-10-10 12:00 2022-09-06 12:00 What I've tried >>> from django.db.models.functions import TruncHour >>> from django.db.models import Max >>> InventoryForecast.objects.annotate( hour=TruncHour('forecast_for') ).values('hour').annotate( most_recent_forecasted_at=Max('forecasted_at') ).values('hour', 'most_recent_forecasted_at') SELECT DATE_TRUNC('hour', "app_inventoryforecast"."forecast_for" AT TIME ZONE 'UTC') AS "hour", MAX("app_inventoryforecast"."forecasted_at") AS "most_recent_forecasted_at" FROM "app_inventoryforecast" GROUP BY DATE_TRUNC('hour', "app_inventoryforecast"."forecast_for" AT TIME ZONE 'UTC') LIMIT 21 Execution time: 0.000353s [Database: default] <QuerySet [{'hour': datetime.datetime(2022, 10, 10, 12, 0, tzinfo=<UTC>), 'most_recent_forecasted_at': datetime.datetime(2022, 9, 6, 11, 0, tzinfo=<UTC>)}, {'hour': datetime.datetime(2022, 10, 10 , 11, 0, tzinfo=<UTC>), 'most_recent_forecasted_at': datetime.datetime(2022, 9, 6, 11, 0, tzinfo=<UTC>)}]> That works correctly in the GROUP BY, but I need the … -
I have an error "TypeError: can't multiply sequence by non-int of type 'str'"
Throwing an error "TypeError: can't multiply sequence by non-int of type 'str'" text1 = "Hello" text2 = "World" result = text1 * text2 print(result) Error message: result = text1 * text2 TypeError: can't multiply sequence by non-int of type 'str' -
Django - compare values of keys in dictionaries in two different lists
I have two lists of dictionaries that I have pulled from an XML file using elementtree. Each list of dictionaries contains dozens of keys/values but for simplicity sake let's say it's similar to the below: list1 = [{'id': '100', 'first_name': 'john'}, {'id': '101', 'first_name': 'joe'}] list2 = [{'id': '100', 'last_name': 'doe'}, {'id': '101', 'last_name': 'bloggs'}] I'm using Django to build a table with the data and want to put the first names (from list1) and last names (from list2) on the same row of the table where there's a match in the 'id' values, but I can't figure out how to do this. If I wanted to list them in python I would use: for v in list1: print(v['id']) print(v['first_name']) for i in list2: if i['id'] == v['id']: print(i['last_name']) But I can't figure out how to write this with django tags in the HTML template. Here's what I've tried (and variations thereof): {% for v in list1 %} <tr> <td>{{v.id}}</td> <td>{{v.first_name}}</td> {% for i in list2 %} {% if {{v.id}} == {{i.id}} %} <td>{{i.last_name}}</td> {% endif %} {% endfor %} </tr> {% endfor %} -
Django notification hq mark_as_read
I am using django-notifications-hq for make notifications working on a Django app. I am having problems with the function "mark_as_read". What I am trying to achieve is to have a notification list and, when clicking on a notification, mark it as read and redirect to the url of the post. The problem is that, basically, I am having problems with that. I tried many different ways on the template such as: <a href="{% url 'main:question_details' pk=notification.target.question.id slug=notification.target.question.slug %}?next={{notification.mark_as_read}}" class="text-reset notification-item"> {% if notification.unread == True %} <div class="d-flex alert-warning"> {% else %} <div class="d-flex"> {% endif %} <div class="flex-1"> <span class="text-dark small">Commento</span> <span class="text-dark small float-end"><i class="mdi mdi-clock-outline"></i> {{notification.timestamp|naturaltime}}</span> <h6 class="mb-1">{{notification.verb}}</h6> <div class="font-size-12 text-muted"> <p class="mb-1">{{ notification.target.comment }}</p> </div> </div> </div> </a> In this case the redirect works but, as soon as I press the dropdown menu, the notification is already marked as read. If I remove the ?next={{notification.mark_as_read}} the redirect works but the notification isn't marked as read. Anyone has ever worked with django notifications had an issue like that? -
Why am I getting No module named 'django.utils.lru_cache' error?
I am working a Django project. I have created a form and tried to use Crispy-forms to style the form. However, when I runserver I get the following error. File "D:\Django_Project\venv\lib\site-packages\django\template\backends\django.py", line 131, in get_package_libraries raise InvalidTemplateLibrary(django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to 'crispy_forms.templatetags.crispy_forms_field': No module named 'django.utils.lru_cache' This is the template where I am using crispy-forms {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %}``` I am using Django==4.0.6 Crispy-form==1.14.0 Have searched online for possible fix unsuccessfully. Please I need help. -
How to upload file from request to google drive using django
I made a web with django, where when I upload a file with a form, the file will be uploaded to google drive. The question is how do I get the file that I got from request.FILE['file'] to upload to google drive? this my code user = request.user.social_auth.get(provider='google-oauth2') tfile = request.FILES['file'] drive = build('drive', 'v3', credentials=Credentials(user)) media_metadata = { 'name': tfile, 'parents': [folder.objects.filter(user__username=user)[0].id_folder] } media = MediaFileUpload(tfile, mimetype='image/jpeg') upfile = drive.files().create(body=media_metadata, media_body=media, fields='id').execute() -
Django - Can't import other app's model from same directory
I've got a problem with importing model from another app for Foreign key. I tried two ways to use field from other model: Import it as a string, it doesn't provide any errors before migrating model: from_city = models.ForeignKey('cities.City', blank=True, null=True, related_name='from_city_set', on_delete=models.CASCADE) It provides an error when i'm trying to use "makekigrations" or "migrate" command Import it as python object, but there is a strange moment. It tries to import 'city' app from src folder like that: from src.cities.models import City from_city = models.ForeignKey(City, blank=True, null=True, related_name='from_city_set', on_delete=models.CASCADE ) Both variants provides the same traceback: Traceback (most recent call last): File "C:\TrainProject\src\manage.py", line 22, in <module> main() File "C:\TrainProject\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\TrainProject\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 196, in handle loader.project_state(), File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\operations\models.py", line 724, in state_forwards state.alter_model_options( File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\state.py", line … -
Django Unit Tests - Changes to self properties are persisting from test to test
I have a test class that has a setup like this. We import a dictionary from a test_helpers file that has some default data. The data is set as FORM_DATA['value_A'] = 0 and FORM_DATA['value_B'] = 1000000 from the start. Whether I set FORM_DATA to a self.form_data value, or assign it to a variable in each test, doesn't matter. The 2nd test seems to persist the dictionary changes from the 1st test, which is not ideal for testing. I added a bunch of print debug statements to show what is happening. Even in the setUp() for the 2nd test, it shows the values from the previous test! What is happening here? Why can't the dictionary self.form_data be the default imported data every time I have a new test? from test_helpers import FORM_DATA class TestBaselineScenarios(TestCase): @classmethod def setUpClass(cls): super(TestBaselineScenarios, cls).setUpClass() long_running_data_setup() def setUp(self): self.form_data = FORM_DATA print("setUp", self.form_data['value_A'], self.form_data['value_B']) def test_one(self): print("1") print(self.form_data['value_A'], self.form_data['value_B']) self.form_data['value_A'] = 25000 self.form_data['value_B'] = 700000 print("2") print(self.form_data['value_A'], self.form_data['value_B']) simulation = test_helpers.create_simulation(form_data=self.form_data) simulation.run() self.assertEqual(0.8416667, round(simulation.success_rate(), 7)) def test_two(self): print("3") print(self.form_data['value_A'], self.form_data['value_B']) self.form_data['value_A'] = 10000 print("4") print(self.form_data['value_A'], self.form_data['value_B']) simulation = test_helpers.create_simulation(form_data=self.form_data) simulation.run() self.assertEqual(0.9916667, round(simulation.success_rate(), 7)) setUp 0 1000000 1 0 1000000 2 25000 700000 setUp 25000 700000 3 25000 … -
How to deploy Django 3 and Vue JS 3 website on AWS? [closed]
I am trying to deploy my app which has Django as the backend and Vue JS CLI as the frontend on AWS. It is using Django REST framework to send and receive data. I was able to deploy the Django app on AWS using Elastic Beanstalk but now how do I deploy the Vue JS app and how do I connect the two in the same way that they do locally. I am new to deployment so any help will be appreciated. -
get the incorrect data from serializer.data
i want to get the data (amount) from serializer but the serializer get back the none. but when i get the date from the request data i get the correct data.can someone help to solve this issue?? this is the response body of serializer data and request data. got the {'amount': 1000000} the request body and the {'amount': None} from serialized data: System check identified no issues (0 silenced). August 23, 2022 - 16:19:21 Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. {'amount': 1000000} {'amount': None} Internal Server Error: /api/zarinpal/request/ Traceback (most recent this is the function get the request @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def request_to_pay(request): data = request.data print(data) serializer = RequestToPaySerializer(data=data) serializer.is_valid(raise_exception=True) print(serializer.data) and this is the serializer class: class RequestToPaySerializer(serializers.Serializer): amount = serializers.DecimalField(max_digits=20, decimal_places=3) description = serializers.CharField(required=False) -
Combine 2 models table data into 1 model (table),Django
models.py: class NewJsonData(models.Model): speed = models.IntegerField() heading = models.IntegerField() altitude = models.FloatField() accuracy = models.FloatField() longitude = models.FloatField() altitudeAccuracy = models.FloatField(null=True) latitude = models.FloatField() pass class NewApiJsonData(models.Model): _id = models.CharField(null=True, max_length=100) coords = models.ForeignKey( NewJsonData, on_delete=models.CASCADE, null=True, blank=True) mocked = models.BooleanField() timestamp = models.FloatField() _v = models.IntegerField(null=True) createdAt = models.CharField(null=True, max_length=100) updatedAt = models.CharField(null=True, max_length=100) I was trying to create a new table having contents of both models as seen in below picture. Table of NewJsonData looks as: and table of NewApiJsonData looks as: -
How to send the data from @property field to database tables in Django
I have a DocumentModel containing some fields including document which is a filefield. I have used @property decorator to get the name, size and mime type of a file which gets uploaded. The issue that currently i am facing is that @property fields are being shown on frontend in serializers, but its not being show in database tables. In database tables only id, document, and created_at is being shown but not filename, filesize, and mimetype Kindly if someone can guide how can i send this @property data to database tables? Models.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField(max_length=350 ,validators= [FileExtensionValidator(extensions)]) created_at=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def filename(self): return self.document.name @property def mimetype(self): return mimetypes.guess_type(self.document.url)[0] serializers.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model=DocumentModel fields = ['id', 'document', 'filesize', 'filename', 'mimetype', 'created_at'] -
Django-rest framework and Client Credentials grant type with no user
I am using the Django-rest framework for implementing a set of APIs using the Client Credentials grant type.The Client Credentials grant type is used by clients to obtain an access token outside of the context of a user. My " authenticate" method isn't tied to a user, nor should be. However, Django rest according to the documentation expects a user. "If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None." This means that even tho my token is valid Django rest will still give permission denied. For example: class TokenAuthentication(BaseAuthentication): """ https://www.oauth.com/oauth2-servers/access-tokens/self-encoded-access-tokens/ """ keyword = 'Bearer' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user_model = get_user_model() def authenticate(self, request): token = get_authorization_header(request).split() if not token or token[0].lower() != self.keyword.lower().encode(): return None if len(token) == 1: raise InvalidTokenHeaders() if len(token) > 2: raise InvalidTokenHeaders() token = token[1] unsigned_claims = self.decode_token_claims_no_key(token) client_id = unsigned_claims.get('sub',None) client = self.get_application_by_client_id(client_id=client_id) if client is None: raise InvalidToken() trusted_cliams = self.verify_token_cliams(token, client.client_secret) request.user = None request.auth = trusted_cliams.get('client_id') return request.user,request.auth -
Django How to cleaify if the value is changed in models save method
I have a model like this one: class Exam(BaseModel): ... STATE_CHOICES = ( (PASS, PASS), (FAILED, FAILED), (GREAT, GREAT), state = models.CharField(max_length=15, choices=STATE_CHOICES, default=PASS) ... Now I want orderride the save method and know if the state field is changed or not: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.__state != self.state: print('changed') super().save(force_insert, force_update, using, update_fields) The self.__state seems wrong, how can I do that? -
how to run existing Django project
I'm new with python(don't know anything about it), and also in Django... so question is, what and how, step by step, I need to launch existing Django project which I got from github... so, what I have done already: installed python created virtual environment run python mange.py migrate, but it showed many errors(and I don't know what to do with it and how to fix them), because I can't even connect to DB(previously I worked with MySQL where I can connect by myself and do selects to check something in DB), but now this project uses SQLite3, and I don't know how I can check this database run python manage.py runserver and I can see my webapp at localhost... So, main question is, how to properly launch existing Django project? -
How to relationship such a connection in django?
I need to implement a "end-to-end" connection between products. like this I automatically put down two-way links between two products. But when I link product A to product B and product B to product C, there is no connection between A and C. It is necessary that they communicate themselves when putting down the two previous links. Models.py from django.db import models class Part(models.Model): brand = models.CharField('Производитель', max_length=100, blank=True) number = models.CharField('Артикул', max_length=100, unique=True) name = models.CharField('Название', max_length=100, blank=True) description = models.TextField('Комментарий', blank=True, max_length=5000) analog = models.ManyToManyField('self',blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.number) return self.name class Meta: verbose_name = 'Запчасть' verbose_name_plural = 'Запчасти' -
Searching fields from other models
I'm creating an API where I need to fetch and copy information from another model within the application. I am aware of the function that comes in the Django Rest Framework, SearchFilter, but it only works within the same model. class BookingViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend, SearchFilter,] serializer_class = BookingSerializer filterset_class = BookingFilter search_fields = ['full_name', 'email'] Below is the function I managed to create to get the data from the client model, but I can only get them all at once. I would choose and take one by one @action(detail=False, methods=['GET', 'delete'], name='Get The Client') def get_client(self, request): queryset = Client.objects.filter(is_active=True) client = get_object_or_404(queryset) serializer = ClientSerializer(client) return Response(serializer.data) -
Django - request.user returns AnonymousUser with custom user
I am having some problems on the authentication part for my Django app, using a CustomUser. The logic is the following: I need to send credentials (email/password) to an external API, from which I retrieve the access token which will be used on the later requests. During the process, I also create (or update, if it's already there) a CustomUser inside my local db, with the same credentials as in the external database. Then I try to authenticate the user in my app with the same credentials. Below the relevant parts of code: models.py: class CustomUser(AbstractUser): email = models.EmailField("Email", max_length=255, unique=True, null=True) custom_user_id = models.IntegerField("Custom user id", unique=True, null=True) name = models.CharField("Name", max_length=255, null=True) initials = models.CharField("Initials", max_length=255, null=True) views.py from django.contrib.auth import login as auth_login @api_view(['POST']) @never_cache def user_login(request): ''' User login ''' if request.method == 'POST': url = "THE EXTERNAL API" payload = { 'email':request.data['email'], 'password':request.data['password'] } headers = { 'Origin': 'REDACTED', 'Content-Type': 'text/plain' } email = request.data['email'] username = email password = request.data['password'] payload = '{"email":"' + email + ',"password":"' + password + '}' r = requests.post(url, data = payload, headers=headers) if r.status_code == 200: data = r.json() # Get user // create one if it doesn't … -
Can't save modified models.py because of (already applied) migration file - Django 3
I previously added 2 functions in my models.py for my upload path. But i noticed later the 2 functions were similar. def upload_path(instance, fl_file_name): supplier = str(instance.fl_supplier).replace(' ', '-') return ('sources/{0}/{1}'.format(supplier.lower(), fl_file_name)) def upload_path_stock(instance, fl_file_name): supplier = str(instance.fl_st_supplier).replace(' ', '-') return ('sources/{0}/{1}'.format(supplier.lower(), fl_file_name)) A bit lower, my model was written like this class Flow(models.Model): [...] fl_file_name = models.FileField( max_length=50, upload_to=upload_path_stock, verbose_name='Nom fichier') I tried to comment the function def upload_path_stock and changed the property of my model like this : class Flow(models.Model): [...] fl_file_name = models.FileField( max_length=50, upload_to=upload_path, verbose_name='Nom fichier') # <<<< HERE But when saving, an error raised : File "/Users/[...]/migrations/0063_auto_20220822_1834.py", line 27, in Migration field=models.FileField(max_length=50, upload_to=flows.models.upload_path_stock, verbose_name='Nom fichier'), AttributeError: module 'flows.models' has no attribute 'upload_path_stock' This line prevents saving the file to be saved because upload_path_stock is mentioned there: migrations.AlterField( model_name='flowstock', name='fl_st_file_name', field=models.FileField(max_length=50, upload_to=flows.models.upload_path_stock, verbose_name='Nom fichier'), ), So I uncommented the unwanted function and proceed again with a new migration. Now the last migration is #64. But even though the migration 64 is applied, the error is still mentioned in the 63 when I comment out the function again and try to save my model. Can I modify the new path directly in migration 63 file or should … -
Spotipy not changing users
So I am making a Spotify statistics app which just shows some stats about the user's Spotify account using the Django and the Spotipy python module. I made the user's first name a required field and labeled it Spotify Username so that the user enters their Spotify username and it is stored in the users table as the first_name (I realize the flaws with this approach, I am just trying to get everything up and running). My problem is that no matter how many times I logout and switch users, the responses from the Spotify api don't change. Take for example this function: @login_required def recents(request): token = spotipy.util.prompt_for_user_token( username=request.user.first_name, scope=SCOPE, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI) session = spotipy.Spotify(auth=token) recents = session.current_user_recently_played(limit=8) recents = recents["items"] return render(request, 'stats/recents.html', { "recents": recents }) I specify username=request.user.first_name but the recents page for every user shows the recent songs on my own Spotify account. I have a hunch that this is because my REDIRECT_URI is http://localhost:8080/ so it is automatically signing into my own account, however I'm not sure.