Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: Upload many similar files
I have created a user API for uploading documents. The link to the file is stored in license_* type fields, the document status is stored in license_*_status. models.py @deconstructible class User_directory_path(object): def __init__(self, prefix): self.prefix = prefix def __call__(self, instance, filename): return f'{instance.id}/{self.prefix}_{filename}' class Profile(models.Model): class DocumentStatus(models.TextChoices): NOT_UPLOADED = 'NOT_UPLOADED' ON_REVIEW = 'ON_REVIEW' ACCEPTED = 'ACCEPTED' id = models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) license_0 = models.FileField(verbose_name='License(1)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_0'), max_length=255, null=True, blank=True) license_0_status = models.CharField(verbose_name='License(1) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_1 = models.FileField(verbose_name='License(2)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_1'), max_length=255, null=True, blank=True) license_1_status = models.CharField(verbose_name='License(2) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_2 = models.FileField(verbose_name='License(3)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_2'), max_length=255, null=True, blank=True) license_2_status = models.CharField(verbose_name='License(3) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_3 = models.FileField(verbose_name='License(4)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_3'), max_length=255, null=True, blank=True) license_3_status = models.CharField(verbose_name='License(4) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_4 = models.FileField(verbose_name='License(5)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_4'), max_length=255, null=True, blank=True) license_4_status = models.CharField(verbose_name='License(5) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) In this example, the user can submit 5 licenses. The field names are similar, only the postfix changes. Should I use this approach when uploading a large number of similar files? -
Hi guys, i'm new in python, why i can't call fuctions two time(in if and in else)?
class Get_Cost_Mixin: def get_name(self): if len(list(self.ingredients.split())) <= 1: call.get_cost() <------ call.get_price() <------ print(str(self.ingredients) + ' Smoothie') else: call.get_cost() <------ call.get_price() <------ print(str(self.ingredients) + ' Fusion') Hi guys, i'm new in python, why i can't call fuctions two time(in if and in else)? -
Django - models with relations to possibly nonexisting users
I am working on an enterprise LMS powered by Django REST framework. Authentication is done via Google OAuth 2.0 using the package drf-social-oauth2, and the target organizations for my software are schools and universities. Some models have foreign keys to the user model; however, due to the nature of my application, oftentimes a user may want to reference a user that isn’t present in the database yet. This happens because users are created in the database upon their first login in the application via OAuth, yet the person who wants to create a specific model instance referencing another user may want to do so before they’ve logged in for the first time: for example, a teacher may want to pre-enroll a list of students into their new course, but those users might not have logged in for the first time yet, and therefore might not exist in the database. I’ll give a concrete example with a model in my application: class UserCoursePrivilege(models.Model): """ Represents the administrative permissions a user has over a course. See logic.privileges.py for the available permissions. """ user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="privileged_courses", ) course = models.ForeignKey( Course, on_delete=models.CASCADE, related_name="privileged_users", ) allow_privileges = models.JSONField(default=list, blank=True) deny_privileges = … -
How to force link opening oustide of embedded browser / webview?
I setup a simple authentication system using python-social-auth-django. Everything is working fine on my computer and my mobile phone, but when I try to open login link from Messenger app with another phone (Huawei brand), the link opens inside Messenger's embedded browser and I get belows (same for Facebook and Google oauth). Searching around it has something to do with new policy disabling authentication from embedded browser such as Messenger embedded browser. What should I do either to force my login link to open outside of Messenger embedded browser or allow login with Facebook/Google oauth from WebViews browser ? You can't sign in from this screen because this app doesn't comply with Google's secure browsers policy. If this app has a website, you can open a web browser and try signing in from there. From my browser and own phone I open home link (from messenger app). This opens a browser window and login works fine. From another phone, when I click the messenger link, it opens in embedded browser. -
Next13 fetch to localhost:8000 does not work
Somehow the fetch from next13 doesnt work with Django on localhost:8001. I get the following error: TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { cause: Error: [object Object] at makeNetworkError (node:internal/deps/undici/undici:6317:51) at httpNetworkFetch (node:internal/deps/undici/undici:7810:16) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33) at async httpFetch (node:internal/deps/undici/undici:7557:37) at async schemeFetch (node:internal/deps/undici/undici:7489:18) at async node:internal/deps/undici/undici:7342:20 at async mainFetch (node:internal/deps/undici/undici:7338:20) { [cause]: undefined } } TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { digest: '1117663215' with this code: import './globals.css' export default async function RootLayout({ children, }: { children: React.ReactNode }) { // const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' }); const data = await fetch(`http://localhost:8001/board/`, { method: 'GET', headers: { 'Accept': 'application/json', "Content-Type": "application/json" }, redirect: 'follow', cache: 'force-cache' }); console.log(data) return ( <html lang="en"> <head /> <body> <h1></h1> <div>{children}</div> </body> </html> ) } Fetching from any other public api works. CORS is enabled and CORS_ORIGIN_ALLOW_ALL = True is set in the Django settings.py Any idea how I can fix this? Thanks -
django queryset error when use len(qs) TypeError: argument must be int or float
I dont know what happened with my db but now I can not len my queryset. I can make a qs with a lot of obj with qs.SignalSma.objects.all() But somehow I can not use len(qs) on that qs or make a loop with that qs I am getting in this error if I try to do so. In [9]: len(qs) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 1 ----> 1 len(qs) File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:262, in QuerySet.__len__(self) 261 def __len__(self): --> 262 self._fetch_all() 263 return len(self._result_cache) File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:1324, in QuerySet._fetch_all(self) 1322 def _fetch_all(self): 1323 if self._result_cache is None: -> 1324 self._result_cache = list(self._iterable_class(self)) 1325 if self._prefetch_related_lookups and not self._prefetch_done: 1326 self._prefetch_related_objects() File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:68, in ModelIterable.__iter__(self) 59 related_populators = get_related_populators(klass_info, select, db) 60 known_related_objects = [ 61 (field, related_objs, operator.attrgetter(*[ 62 field.attname (...) 66 ])) for field, related_objs in queryset._known_related_objects.items() 67 ] ---> 68 for row in compiler.results_iter(results): 69 obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) 70 for rel_populator in related_populators: File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\sql\compiler.py:1122, in SQLCompiler.apply_converters(self, rows, converters) 1120 value = row[pos] 1121 for converter in convs: -> 1122 value = converter(value, expression, connection) 1123 row[pos] = value 1124 yield row File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\backends\sqlite3\operations.py:313, in DatabaseOperations.get_decimalfield_converter.<locals>.converter(value, expression, connection) 311 def converter(value, expression, connection): 312 … -
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed When I create a new django project, everything works as it should, but as soon as I change something, I get this error on any command in terminal. For example python manage.py runsever or python manage.py makemigrations....Any ideas? -
I have one table with a foreign key to another table? is it possible to populate the foreign key and another field from the same tabe?
I have a table properties_numBed, Each of our properties has a bedroom number assigned to it. What I am trying to achieve is that in the DoorCodes class, We first select the PropertyName(already available from the other table, and then the list of bedrooms attached to that property will populate bedroomnumb(field) (properties.models.py) class Properties_NumBed(models.Model): PropertyAddress = models.ForeignKey(Properties,on_delete=models.PROTECT) NumbBedrooms = models.ForeignKey(Properties_Bedrooms,on_delete=models.PROTECT,default=".") class Meta: db_table = "properties_numbBed" def __str__(self): return str(self.PropertyAddress) doorcodes.models.py class DoorCodes(models.Model): id = models.AutoField(primary_key=True) PropertyName = models.ForeignKey(Properties_NumBed, null=True, related_name='PropertyName', on_delete=models.PROTECT) bedroomnumb = models.ForeignKey('Properties_Numbed' , on_delete=models.PROTECT, default='0', db_index=False, related_name='+') lockcode = models.CharField(max_length=10,null=False, default='0000') active = models.BooleanField(default=True) class Meta: db_table = "lesterdoorcodes" ordering = ['PropertyName'] def __str__(self): return str(self.PropertyName) I have spent many hours trying to google this. Is it not possible to access a foreign key as well as a second or third field? Sorry if this has been asked and answered multiple times in the past. I have not been able find a solution. -
Delete attachment in django
I have some points with unique identifiers. Each point has a file attached to it. How do I delete files at a specific point? https://github.com/testdrivenio/django-ajax-xhr/blob/jquery/static/main.js#L19-L41 -
Redis django connects to localhost redis, even when I change URL and PORT
return { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': f'redis://{self.REDIS_URL}:{self.REDIS_PORT}', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } this is my redis code to put in CACHES, still even after specifying different redis_url and port, connects to localhost 127.0.0.1:6379 I want to connect to a different IP url and PORT. I tried different 'BACKENDS' and CLIENT_CLASS and pools, playing around with different CACHES types. I can connect to my url-port redis using this: return redis.StrictRedis(host=self.REDIS_URL, port=self.REDIS_PORT, db=0, decode_responses=True, encoding="utf-8") but not when I want to setup CACHES. -
Are Django models "db_tablespace" equivalent to Postgres Schemas?
I just stumbled with the Django docs reference to db_tablespace option in Meta(), and I'm unsure: Are "tablespaces" (as defined in Django) somewhat equivalent to "schemas" (as defined and used in Postgres)? For example: Would the following models: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Meta(): db_table = 'person' db_tablespace = 'people' class Book(models.Model): author = models.ForeignKey(Person) title = models.CharField(max_length=100) class Meta(): db_table = 'book' db_tablespace = 'books' ... be mapped to Postgres schemas / tables people.person and books.book? -
How to print leaflet map in pdf using django-wkhtmltopdf?
I have a django app I am trying to print a leaflet map in pdf using django-wkhtmltopdf, but the map is not rendering correctly. I even try to give more time to the 'javascript-delay' parameter but is giving me the same result. Here is the image of the map: from wkhtmltopdf.views import PDFTemplateResponse class MyPDFView(View): template='agrimensuras/project_pdf.html' # the template def get(self, request, pk): project = get_object_or_404(Project, id = int(pk)) data = {"project": project} response = PDFTemplateResponse(request=request, template=self.template, filename="hello.pdf", context= data, show_content_in_browser=False, cmd_options={'margin-top': 10, "zoom":1, "viewport-size" :"1366 x 513", 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True}, ) return response In the template (I am just showing the relevant pieces of code): <!--Importing leaflet--> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script> <!--Defining the div--> <div id="map" ></div> <!--Defining the map--> <script type="text/javascript"> var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { minZoom: 5, maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); var marker = L.marker([51.5, -0.09]).addTo(map); var circle = L.circle([51.508, -0.11], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: 500 }).addTo(map); var polygon = L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map); </script> -
Django, Celery, and Celery beat via Copilot. Use Sidecars or multiple services?
I am able to easily deploy a Django application via Copilot. But now I need a Celery worker and beat. Sidecars sounds like what I want. Basically, define two new sidecars: one for a Celery worker and another for a Celery beat. But then I came across Developing an application based on multiple microservices using AWS Copilot and AWS Fargate. This takes the approach of deploying the other docker containers as their own services. It's not exactly clear to me which approach is best for my needs. Sidecars seems simpler and more straight forward. The only thing unclear to me on how to establish with it is the image (required) parameter. Why a URL? Why not a reference to the Dockerfile to build the worker and another one for the beat? -
Can't upgrade Jawsdb plan
I have an app hosted on heroku with a shared database tenant and now i want to upgrade to a single tenent. I love jawsdb but it just wouldn't let me upgrade it saying that it is limited to customers with an established payment history. I have already paid a month for their services but still get this error when upgrading from Leopard Shared to Whitetip plan. Pls help -
django main.app_table__old Error deleting item
I am facing this problem and I tried many solutions but no one works for me or it is not convinient of my case. First I use Django==2.0 (can't change to version due to problems). I have I model table named table and my app is appwhen developing it happend that I can't delete any element in that table (the other works fine). and I get this problem. OperationalError at /fieldsdetails/25/delete/ no such table: main.app_table__old I tried to delete all migrations history so the db.sqlite3 and run: python manage.py makemigrations python manage.py migrate Then I tried to delete the table as python manage.py dbshell SELECT * FROM sqlite_master WHERE type='table'; then I found a table named app_table__old and deleting it using this: DROP TABLE app_table__old .exit but nothing works? is there any solution I don't want to upgrade Django version or lose data. -
What is the second argument to ForeignKey in the django stubs typehints?
order = models.ForeignKey["ExtensionOrder", **WhatGoesHere**]( "subscriptions.ExtensionOrder", null=False, on_delete=models.PROTECT ) The stub is here: class ForeignKey(ForeignObject[_ST, _GT]): _pyi_private_set_type: Union[Any, Combinable] _pyi_private_get_type: Any ... # class access @overload # type: ignore def __get__(self, instance: None, owner) -> ForwardManyToOneDescriptor: ... # Model instance access @overload def __get__(self, instance: Model, owner) -> **_GT**: ... # non-Model instances @overload def __get__(self: _F, instance, owner) -> _F: ... Pylance is griping about it, but I'm not sure what _GT should be -
Serving react build folder in django, page not found on reload
I'm writing a chat application in Django and using React as the front end, I'm serving the react at root path 'localhost:8000/' and there are some path in the react app too such as 'chat/:user', I can access this as long as I go from the root path, if I enter the path manually or try reloading the page it gives the error 'Page not found'. This is my urls.py file from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('', TemplateView.as_view(template_name='index.html'), name='chat'), path('api-auth/', include('rest_framework.urls'), name='api-auth'), path('api/', include('api.urls')), ] and this is my App.js function App(props) { const [user, setUser] = useState('none'); useEffect(() => { fetch('http://localhost:8000/api/user-data') .then((response) => response.json()) .then((data) => { setUser(data.username); }); }, []) //console.log(window.location.href); return ( <BrowserRouter> <Routes> <Route path='/' element={<Layout user={user} socket={props.socket} />}> <Route index element={<Home user={user} socket={props.socket} />} /> <Route path='chat/:chattingUser' element={<ChatPage user={user} socket={props.socket} />} /> <Route path='search/:queryText' element={<SearchPage user={user} socket={props.socket} />} /> </Route> </Routes> </BrowserRouter> ); } I was at the route /chat/ and I changed some things in the code so had to reload the page, then this error came, why is it looking at django urls when i reload and how … -
Why is django-autocomplete-light single-select badly styled and broken when multi-select is working?
I have a screen in Django with a single-select autocomplete and multi-select autocomplete to the same model object (but different model fields). The multi-select is working perfectly, the single-select is functional, but poorly styled and also slightly broken (takes an extra click to get into the box to type). Help? EDIT: If I remove the multi-select box from the form, the single-select is still poorly styled and broken. So, while the multi-select shows something can work, it is likely otherwise unrelated. More detail: Django 4.1.5 django-autocomplete-light 3.9.4 django-bootstrap5 22.2 generated HTML multi-select (working): <span class="select2-selection select2-selection--multiple form-select" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1" aria-disabled="false"><ul class="select2-selection__rendered"><li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" placeholder="Type here" style="width: 288px;"></li></ul></span> .select2-container .select2-selection--multiple: min-height: 32px single-select (broken): <span class="select2-selection select2-selection--single form-select" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-id_primary_diagnosis-container"><span class="select2-selection__rendered" id="select2-id_primary_diagnosis-container" role="textbox" aria-readonly="true"><span class="select2-selection__placeholder">Type here</span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span> "display:inline prevents height:28px from having an effect" In forms.py: class MyobjForm(forms.Form): # NOTE: can't use ModelForm for various reasons not shown single_select = forms.ModelChoiceField( label='single select', queryset=Myobj.objects.all(), widget=autocomplete.ModelSelect2( url="myobj-autocomplete", attrs={ "data-placeholder": "Type here", # Only autocomplete after 1 character has been typed "data-minimum-input-length": 1, }, ), ) multi_select = forms.ModelMultipleChoiceField( label='multi select', queryset=Myobj.objects.all(), required=False, widget=autocomplete.ModelSelect2Multiple( url="myobj-autocomplete", attrs={ … -
cannot import name 'Categories' from partially inisialized module 'categories.models' (most likly due to a circular import)
I try to create 2 database categories and sous_categories in Django. in these 2 database a categories can have many sous_categories and sous_categories has only one categories. When i test my code i got the 'cannot import name 'Categories' from partially initialized module 'categories.models' (most likely due to a circular import)'. I think the error occurs to a circular dependency and the most solution i see int the web is: it can be resolved by moving the imported classes to a third file and importing them from this file. But i don't know how to do it with my code. here part of my categories model: class Categories(models.Model): nom_categorie = models.CharField(max_length=200) marchand = models.ManyToManyField(Marchands) sous_categorie = models.ManyToManyField(Sous_Categories) slug = models.SlugField(default='') images = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(null=True)``` ` and my sous_categories model: ``from django.db import models from django.template.defaultfilters import slugify from categories.models import Categories class Sous_Categories(models.Model): nom_souscategorie = models.CharField(max_length=200) categorie = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, blank=True) slug = models.SlugField(default='') images = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(null=True)`` -
Django localhost default port already in use with postgres
I am receiving a error when running postgres, pgadmin and django. Port is already in use. I know how to use the sudo command to kill the server, however I am not being shown my databases in postgres. It just shows running when I start the server. When I create a new port database shows but doesn't migration the data. Also when I run migrations to django I get error, table already exist and or table doesn't exist. This happens everytime as if there is a duplicate database and it's not connected to the one showing in pgadmin. I tried dropping and deleting tables in pgadmin, and still get table exist. How do i fix this? How do I show all databases connected and delete the one that overrides my default port and have postgres show database servers in the app. Thank you in advance. Long post but I'm stressing and cant find a solution. Deleting tables in pgadmin, change port number, open postgres first than start pgadmin. -
Django save_m2m() in a separate, delayed transaction
I'm facing a vexing issue in which two adjacent lines of code seem to be committed separately to the database- with one of them hanging out for a full day or more before getting committed. if form.is_valid(): instance = form.save(commit=False) if form.cleaned_data['assigned_to_mtm'].count() <= 0: instance.status = "Unassigned" elif instance.status == 'Unassigned': instance.status = "Assigned" instance.save() form.save_m2m() With the above, I am finding the assigned_to_mtm reflected right away in the database. The status, however, isn't. Instead, when a separate save (even happening the next day) updates the status to something else, then this saved status comes in right afterward with the same timestamp, reverting its value to what it should have been at the time the mtm was saved. I'm astonished that I can't get these two to just happen in a single transaction (I tried the @transaction.non_atomic_requests decorator and doing it myself- that didn't help), let alone that the instance.save() hangs out uncommitted for so long, then gets committed only when the status is updated again separately. I might not even care, if the order of saves was at least preserved, but confoundingly, my earlier save is always committed after the next save. What am I doing wrong here? Can … -
how can show profile User in html django
i create user auth and make model profile user with signals to create profile like User but i want show user profile in template ---- model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) ---- path path('profile/<int:id>', views.profile, name="profile") ----- views def profile(request, id): ff = profile.objects.get(id=id) context = {'ff' : ff} return render(request, 'profile.html', context) views not work i dont know the problem in html... {% url 'profile' profile.id %} how can show profile User in html django -
djangochannelsrestframework problem with elastickbeanstalk and @model_observer
I have a consumers in which there is tracking of model changes using @model_observer. I subscribe to the event via @action and track its changes, everything works perfectly locally, the model has changed, I immediately received a change. But as soon as I try to put it on aws elastic beanstalk, I can subscribe/unsubscribe, but I don't get changes about events, although I see that the session is not broken. I thought that the problem was in queues or sessions, but I checked this together with technical support, they told me that everything was working correctly and the connection was made correctly. Maybe you know at least in which direction I should look and dig? Just in case, I summarize: everything works correctly locally, when uploading to the server, only subscribe to the event / unsubscribe from the event works, but for some reason the changes do not work my consumer.py with @model_observer my django.conf my Procfile: web: gunicorn --bind :8000 --workers 3 --threads 2 settings.wsgi:application websocket: daphne -b 0.0.0.0 -p 5000 settings.asgi:application I watched redis, I watched DB, cleaned up sessions -
client.post is not passing the FK
Hope someone can help me out here, I am trying to test a post method on an API, but the post method is not working as expected. When I pass the payload to the post method, the points and de code fields are loaded but the shopper and card fields, which are both Foreing Keys, are not loaded and a null value is passed, as they are required fields I ended up getting an error. I did check, and the values for self.shopper.pk and self.card.pk are correct. MYCARDS_URL = reverse('mycards:mycards-list') def test_create_mycards(self): """Test creating a mycards""" payload = { 'shopper': self.shopper.pk, 'card': self.card.pk, 'points': 0, 'code': "code", } res = APIClient().post(MYCARDS_URL, payload) I did check to see if was something related to my serializer, but it is all good as you can see: class MycardsSerializer(serializers.ModelSerializer): """Serializer for cards.""" class Meta: model = MyCards fields = ['id', 'shopper', 'card', 'updated', 'created'] read_only_fields = ['id', 'created'] class MycardsDetailSerializer(MycardsSerializer): """Serializer for card detail view.""" class Meta(MycardsSerializer.Meta): fields = MycardsSerializer.Meta.fields + [ 'points', 'code'] Here is also my viewset which seems to be ok: class MycardsViewSet(viewsets.ModelViewSet): """View for manage card APIs.""" serializer_class = serializers.MycardsDetailSerializer queryset = MyCards.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Django - can't delete rows when migrating backwards
I have a problem. I implemented a migration to create another option on my model (add the preview textchoice) and implemented a RunPython method to create rows on a table that matches my requirements. This works. The part that doesn't work is the reverse code. I simply query and filter the instances that I want to delete and try to delete them. In doing so, I get this weird error: Unapplying applications.0012_alter_mediatype_name...Traceback (most recent call last): File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 39, in <module> cli.main() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 430, in main run() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 284, in run_file runpy.run_path(target, run_name="__main__") File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 321, in run_path return _run_module_code(code, init_globals, run_name, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 135, in _run_module_code _run_code(code, mod_globals, init_globals, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 124, in _run_code exec(code, run_globals) File "/code/ews/manage.py", line 22, in <module> main() File "/code/ews/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File …