Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
The right order in docker-compose file for django application
I have django-app which has docker-compose: services: web: build: . volumes: - .:/code ports: - "80:80" command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:80" env_file: - ./.env depends_on: - db restart: always (... here postgres, redis and celery) and i have three questions about this: Doest it matter where we specify the ports? I think they should be after ports, but it works too. For example i want run my app on default 127.0.0.1:8000, but if i make: ports: "8000":"8000" ... python manage.py runserver 127.0.0.1:8000 i cant get acess to my app. It works only on localhost when i runserver on 0.0.0.0:8000. Can i run my app on default 127.0.0.1 or localhost only? Is there any "correct" order of components (build, volumes, ports, etc.) for django-app? -
Using django-import-export, how to export M2M field values one -below the other?
I am able to export M2M fields using django-import-export, but the csv has the M2M field values as CSV. How can we print this csv with M2M values one below the other in the column in separate rows in the same column eg: Expected csv: Teacher | Students ----------------- teacher1| student1 student2 student3 teacher2| student22 student1 student 11 student3 -
Animated GIFs not working with Wagtail 3 and Django 4
Issue Summary Install Wagtail with all required dependencies. In order to use a GIF, WAND and imagemagick must be installed. When uploading a GIF file I now get the following error message: All steps have been implemented as specified in the documentation. (https://docs.wagtail.org/en/stable/advanced_topics/images/animated_gifs.html) Unfortunately, the GIF handling with Wagtail currently does not work must be set more, which is not documented? Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead? Steps to Reproduce Install Wagtail with all the libraries in techincal details I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: yes Technical details Django>=4.0,<4.1 wagtail>3 wagtail_localize==1.2.1 django-extensions==3.2.0 psycopg2==2.9.3 loglevel==0.1.2 Wand==0.6.10 Ubunutu Server: sudo apt-get install libmagickwand-dev Local MacOS: brew install imagemagick Thank you very much in advance. I look forward to your feedback. -
CHANNELS DJANGO
I'm trying to get django channels to work with daphne, but I can't connect rooms, the app runs good,but whenever I run the app, and open a "room" websocket it automatically disconnects, it is worth mentioning that my site is running with HTTP and any help will be apreciated 2022-08-19T13:20:57.879758+00:00 app[worker.1]: conn = await self.create_conn(loop) 2022-08-19T13:20:57.879769+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/channels_redis/core.py", line 79, in create_conn 2022-08-19T13:20:57.879862+00:00 app[worker.1]: return await aioredis.create_redis_pool(**kwargs) 2022-08-19T13:20:57.879863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/commands/__init__.py", line 188, in create_redis_pool 2022-08-19T13:20:57.879967+00:00 app[worker.1]: pool = await create_pool(address, db=db, 2022-08-19T13:20:57.879978+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 58, in create_pool 2022-08-19T13:20:57.880062+00:00 app[worker.1]: await pool._fill_free(override_min=False) 2022-08-19T13:20:57.880073+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 383, in _fill_free 2022-08-19T13:20:57.880224+00:00 app[worker.1]: conn = await self._create_new_connection(self._address) 2022-08-19T13:20:57.880233+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 133, in create_connection 2022-08-19T13:20:57.880336+00:00 app[worker.1]: await conn.auth(password) 2022-08-19T13:20:57.880345+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/util.py", line 52, in wait_ok 2022-08-19T13:20:57.880426+00:00 app[worker.1]: res = await fut 2022-08-19T13:20:57.880437+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 186, in _read_data 2022-08-19T13:20:57.880564+00:00 app[worker.1]: obj = await self._reader.readobj() 2022-08-19T13:20:57.880576+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/stream.py", line 102, in readobj 2022-08-19T13:20:57.880669+00:00 app[worker.1]: await self._wait_for_data('readobj') 2022-08-19T13:20:57.880680+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/streams.py", line 502, in _wait_for_data 2022-08-19T13:20:57.880853+00:00 app[worker.1]: await self._waiter 2022-08-19T13:20:57.880863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/selector_events.py", line 854, in _read_ready__data_received 2022-08-19T13:20:57.881081+00:00 app[worker.1]: data = self._sock.recv(self.max_size) 2022-08-19T13:20:57.881108+00:00 app[worker.1]: ConnectionResetError: [Errno 104] Connection reset by peer 2022-08-19T13:20:58.216868+00:00 heroku[worker.1]: Process exited with … -
How can I solve a problem with different behaviour between prod and dev? [closed]
We have an issues with a web application on NextJS + Django Rest Framework. The application is creamscan.com. It is a skin care analyzer web site that looks like ecommerce site with 10 000+ product pages. When product page is loaded for the first time, there are no issues. But when the page is refreshed, different versions of the page come from NextJS. Etag also differs. Pages are not cached, but built directly on a server. The difference between the pages is in the different content of a MobX store. Front and Back are in the docker container, routing is done through traefik. Interestingly enough, the problem occurs only on prod. On the dev server, which is completely identical to the product, except that the dev-server is on a subdomain, everything is fine, the correct version of the page is always loaded during a refresh. Where can you dig, what to look for? Thank you. -
I have to integrate my company's app with Jira using REST api and use the basic authentication.. I have to do it in django structure
So i am asked to create integration with my company application to jira with python django structure. help me defining the code, utils and urls.. I have tried to create the code for getissue and create issue. I am new to python and integration. any help would be great! -
Starting In django 4.1, the auth LogoutView requires a POST (not a GET) request: Is there a built-in form so I can get the CSRF?
As of Aug 23, 2022 (20 days after 4.1 release), google search could not find the answer...! So, asking on SO. -
how to filter from 10 cores data in django orm?
I have a table that contains 10 cores of data and no relation to another table. MySQL database is used. When I try to filter data from the table using ORM it takes 10 to 12 minutes to show the results. is there any solution to minimize the time? -
zipfile.BadZipFile Error after upgrading to Python 3.10 and Django 4
I just updated the version of python from 3.9.13 to 3.10.6 and also upgraded the version of Django from 3.2.2 to 4.0. After resolving all deprecations and other stuff of Django, I still have a strange error for which I can't find any real information. Running migrations: 2022-08-23T09:36:36.225293524Z Applying reversion.0002_add_index_on_version_for_content_type_and_db... OK 2022-08-23T09:36:40.152930290Z Installed 233 object(s) from 3 fixture(s) 2022-08-23T09:36:43.581769579Z Traceback (most recent call last): 2022-08-23T09:36:43.581849467Z File "/srv/odineapps/./manage.py", line 16, in <module> 2022-08-23T09:36:43.583754285Z execute_from_command_line(sys.argv) 2022-08-23T09:36:43.584229050Z File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line 2022-08-23T09:36:43.585537332Z utility.execute() 2022-08-23T09:36:43.585596062Z File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute 2022-08-23T09:36:43.586523094Z self.fetch_command(subcommand).run_from_argv(self.argv) 2022-08-23T09:36:43.586621110Z File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv 2022-08-23T09:36:43.587530652Z self.execute(*args, **cmd_options) 2022-08-23T09:36:43.587625632Z File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute 2022-08-23T09:36:43.588570591Z output = self.handle(*args, **options) 2022-08-23T09:36:43.588673880Z File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 78, in handle 2022-08-23T09:36:43.590102502Z self.loaddata(fixture_labels) 2022-08-23T09:36:43.590219905Z File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 138, in loaddata 2022-08-23T09:36:43.590233030Z self.load_label(fixture_label) 2022-08-23T09:36:43.590237066Z File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 199, in load_label 2022-08-23T09:36:43.590240760Z fixture = open_method(fixture_file, mode) 2022-08-23T09:36:43.590243971Z File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 375, in __init__ 2022-08-23T09:36:43.590247263Z super().__init__(*args, **kwargs) 2022-08-23T09:36:43.590250333Z File "/usr/local/lib/python3.10/zipfile.py", line 1267, in __init__ 2022-08-23T09:36:43.590302006Z self._RealGetContents() 2022-08-23T09:36:43.590312696Z File "/usr/local/lib/python3.10/zipfile.py", line 1334, in _RealGetContents 2022-08-23T09:36:43.590593207Z raise BadZipFile("File is not a zip file") 2022-08-23T09:36:43.590608228Z zipfile.BadZipFile: File is not a zip file 2022-08-23T09:36:48.035918647Z Installed 5 object(s) from 1 fixture(s) 2022-08-23T09:36:48.590917293Z Any idea what this might be? -
Sending data to database with JavaScript in Django
I need to write a compatible algorithm for this code, but I can't. How can I send data to backend? I am using bootstable.js for table HTML table: <table class="table table-bordered" id="table-list"> <thead> <tr> <th></th> <th>Name</th> <th>Slug</th> <th>Email</th> </tr> </thead> <tbody> {% for chart in charts %} <tr> <th id="id">{{chart.id}}</th> <td class="editable" id="name">{{chart.name}}</td> <td class="editable" id="slug">{{chart.slug}}</td> <td>john@example.com</td> </tr> {% empty %} <p>No data</p> {% endfor %} </tbody> </table> And this is my JavaScript code. I tried to try some methods myself but it didn't work <script src="{% static 'npe_cp/js/bootstable.js' %}"></script> <script> //apply $("#table-list").SetEditable(); $('#addRow').click(function() { rowAddNew('table-list'); }); $('#bAcep').on('click', function(){ // var id=$("#id").val(); // var name=$("#name-44").val(); // var slug=$("#slug-44").val(); let name=document.querySelector('#name') console.log(id, name, slug, 'Hello World') $.ajax({ url:"/chart/edit", type:"POST", data:{ "id":id, "name":name, "slug":slug, }, }) }); This is exactly what the table looks like. I want to update, create, and delete operations. But I am not getting the data. -
Django Inherited Model's Serializer
This is my models.py from django.db import models from django.contrib.auth.models import AbstractUser # class User(AbstractUser): # pass class JsonData(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() class Meta: abstract = True class ApiJsonData(JsonData): _id = models.CharField(null=True, max_length=100) # coords = models.ForeignKey( # JsonData, on_delete=models.CASCADE, related_name='coords', 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) and serializers.py: class JsonSerializer(serializers.ModelSerializer): accuracy = serializers.FloatField() altitude = serializers.FloatField() latitude = serializers.FloatField() longitude = serializers.FloatField() heading = serializers.IntegerField() speed = serializers.IntegerField() altitudeAccuracy = serializers.FloatField() class Meta: model = JsonData fields = ['accuracy', 'altitude', 'latitude', 'longitude', 'heading', 'speed', 'altitudeAccuracy'] class ApiJsonSerializer(serializers.ModelSerializer): # coords=JsonSerializer(many=True) _id = serializers.CharField() mocked = serializers.BooleanField() timestamp = serializers.FloatField() _v = serializers.IntegerField() createdAt = serializers.CharField() updatedAt = serializers.CharField() class Meta(JsonSerializer.Meta): model = ApiJsonData fields = ['_id', 'mocked', 'timestamp', '_v', 'createdAt', 'updatedAt'] My json input should be like this: { "_id": "63045167b858bd8b0349638b", "coords": { "speed": 0, "heading": 90, "altitude": 191.89999389648438, "accuracy": 16.527000427246094, "longitude": 77.0809108, "altitudeAccuracy": 13.011088371276855, "latitude": 28.6299509 }, "mocked": false, "timestamp": 1661227133624, "__v": 0, "createdAt": "2022-08-23T04:02:47.272Z", "updatedAt": "2022-08-23T04:02:47.272Z" } I was trying to write serializer for above json so … -
DRF is not hashing password
Here's the model: class CustomerStatus(models.TextChoices): ACTIVE = 'ACT', 'Active' EXPIRED = 'EXP', 'Expired' REVOKED = 'REV', 'Revoked' class Customer(models.Model): email = models.EmailField(max_length=254, unique=True) password = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=3, choices=CustomerStatus.choices, default=CustomerStatus.ACTIVE ) and the serializer: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['email', 'password', 'created', 'status'] extra_kwargs = {'password': {'write_only': True}} But I want to hash the password and that's not working. I check the field in Admin site and it's stored in plain text. I've tried these: def create(self, validated_data): validated_data['password'] = make_password(validated_data['password']) return super(CustomerSerializer, self).create(validated_data) and this one: def create(self, validated_data): validated_data['password'] = make_password(validated_data['password']) return super().create(validated_data) and this one: customer = Customer.objects.create( email=validated_data['email'], password=make_password(validated_data['password']), ) return customer I'm running out of options. -
Able to Access User Dashboard After Logout on Pressing Back with Flask
I am new to flask here have created a basic Login/Logout system which seems to be working fine the issue is if I logout & press Back button I am able to view user dashboard expected is it should redirect to login page , I have added no cache & session but both seems to be useless in my case kindly suggest what's wrong here & how to fix this from urllib import request from webbrowser import get from flask import Flask, render_template, redirect, url_for, flash, session, request from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import Length, EqualTo, DataRequired, ValidationError from flask_login import UserMixin, login_user, login_required, LoginManager, logout_user, current_user from flask_bcrypt import Bcrypt app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///user.db' app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config['SECRET_KEY'] = "Your_secret_string" bcrypt = Bcrypt(app) # declaring bcrypt here app needs to be as arg db = SQLAlchemy(app) # declaring db here loginmanager = LoginManager() loginmanager.init_app(app) # Ensure responses aren't cached @app.after_request def add_header(r): r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public, max-age=0' return r # for login manager # required by flask login to keep track of user in memory reuired … -
Django Annotation, QuerySet, Aggregation method selection and/or Model structure
I am hoping someone can help me with the best way to query my database and/or correcting my model relationships to be able to query the database. I have tried a lot of options with filters, annotation and queryset, but I cannot workout how to structure my query to give the desired outcome. Models.py: from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField from django.db.models.signals import post_save STATUS = ((0, 'Draft'), (1, 'Published')) CABIN_TYPE = ((0, "Shared"), (1, "Private")) CREW_OPTION = ((0, "Passenger Only"), (1, "Prepared to Crew")) SAILING_EXPERIENCE = ((0, "None"), (1, "Some"), (2, "Lots")) class Route(models.Model): route_name = models.CharField( 'Route Name', max_length=200, blank=False, unique=True) description = models.TextField('Description', blank=False) duration = models.IntegerField('Duration (days)', null=False, blank=False) distance = models.IntegerField( 'Distance (nautical miles)', null=False, blank=False) status = models.IntegerField(choices=STATUS, default=0) featured_image = CloudinaryField('Image', default='placeholder') class Meta: ordering = ['route_name'] def __str__(self): return self.route_name class Trip(models.Model): trip_date = models.DateField('Trip Date') route_name = models.ForeignKey( Route, on_delete=models.CASCADE, blank=False, null=True) description = models.TextField('Description', blank=False) status = models.IntegerField(choices=STATUS, default=0) interest = models.ManyToManyField( User, related_name='trip_interest', blank=True) class Meta: ordering = ['trip_date'] def __str__(self): return str(self.trip_date) def expressions_of_interest(self): return self.interest.count() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) bio = models.TextField('Bio', blank=True) sailing_exp = models.IntegerField( 'Previous Sailing … -
which is best subdomain or multiple apps? [closed]
I am doing a Django web application that consists of several sub-services. And now I am confused about creating sub-domain or apps in django. Can anybody help me with the architecture?