Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup nginx config .well-known/acme-challenge with a proxy to Django?
I am very confused with the Nginx .well-known/acme-challenge configuration and how it works with a proxy for Django. Here is my frontend config with is working: server { listen 80; server_name myserve.com; root /var/www/html/myapp_frontend/myapp/; index index.html; location / { try_files $uri$args $uri$args/ /index.html; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://myserver.com$request_uri; } server { listen 443 ssl; server_name myserver.com; location / { root /var/www/html/myapp_frontend/myapp/; index index.html index.htm; try_files $uri$args $uri$args/ /index.html; } ssl_certificate /root/.acme.sh/myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/myserver.com/privkey.pem; } So, on the frontend I have no problem to define: root /var/www/html/myapp_frontend/myapp/; Now I can run the acme script like this: /root/.acme.sh/acme.sh --issue -d myserver.com -w /var/www/html/myapp_frontend/myapp/ It is working fine. But I have issues with my Django backend because the nginx config uses a proxy: upstream myapp { server backend:8000; } server { listen 80; server_name api.myserver.com; location / { proxy_pass http://myapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://api.myserver.com$request_uri; } server { listen 443 ssl; server_name api.myserver.com; location / { proxy_pass http://myapp; } ssl_certificate /root/.acme.sh/api.myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/api.myserver.com/privkey.pem; } Notice that I do not have a configuration for the folder "/var/www/html/myapp_backend/myapp/" as I have on the … -
whats wrong with capturing username in url? Like: mysite.com/username [closed]
I want to create directory something like mysite.com/user models.py class TwitterUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) urls.py urlpatterns = [ path('<str:user>/', views.user_profile, name='user_profile'), ] views.py for that user_profile def user_profile(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/user_home.html', {'user':user}) -
How many create FCM topics in a server
My team was in trouble in push alarm with FCM token in IOS, So we decided to push alarm to each user with topics. I know that "One app instance can be subscribed to no more than 2000 topics." Firebase But i confused about "One app instance". Is that mean each android or ios application user can subscribe 2000 topics? or Each FCM Server can create up to 2000 topics? I wonder about One app instance's meaning in "One app instance can be subscribed to no more than 2000 topics" -
Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is
Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a post can have a null for the parent post attribute - this would denote the "root" post. However, when I implement the views, model and serializer for the posts, I get the following error (stack trace): Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Post.objects.create()`. You may need to make the field read-only, or override the PostSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 564, in __init__ _setattr(self, field.attname, val) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 606, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_post_id.set() instead. Here's my model: class PostObjects(models.Manager): """ Return the Post object and all children posts """ def get_queryset(self): … -
Override django setting only if present in os.environ
I want to define a function that will create a variable under certain circumstances at the scope of where the function was invoked. Something like this: def hook_env(new_var_name, env_var_name): if env_var_name in os.environ: "define new_var_name at the scope in which this function was defined and set it equal to os.environ[env_var_name]" My use case is so I can override Django settings from environment variables, but only present in the environment. Something like this is invalid # only create the variable if some criteria is met def hook_env(new_var, env_name): if env_name in os.environ: global()[new_var] = os.environ[env_name] In C/C++ I might use a macro. I don't know what to do in python. Would it be safe to modify the default variable wherever django creates it in the first place (django/conf/global_settings.py) from inside my settings file? -
whats wrong with capturing user in url?
I want something like mysite.com/user app/urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('<str:user>/', views.user_profile, name='user_profile'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] views.py for that user_profile @login_required @twitter_login_required def user_profile(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/user_home.html', {'user':user}) models.py class TwitterUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) -
django create auto increment custom id
I want to generate a custom id everytime I insert something like { "office": "DORM", "sem": "2", "sy": "2021-2022", "remarks": "TEST", "resolution": "TEST", "studid": "2019-0069" } it will save something like CL-DORM20212022200 (CL-officesysem00) this is my models.py with a default function def get_default_id(): last_cl_itemid = ClearanceItem.objects.all().order_by('cl_itemid').last() if not last_cl_itemid: return 'CL-' + ('DORM') + ('2021-2022') + ('2') + '00' item_id = last_cl_itemid.cl_itemid item_int = item_id[13:17] new_item_int = int(item_int) + 1 new_item_id = 'CL-' + ('DORM') + ('2021-2022') + ('2') + str(new_item_int).zfill(2) return new_item_id for now it's still hardcoded class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' Any idea how can I do this? -
Multi-Table Django Join
Relatively new to Django. I'm building a light CRM in Django. The MYSQL database I built uses associative entities to help deal with many-to-many relationships. I'm trying to use the associative entity "contactdeal" to connect "deals" with "contacts". See models and views below. class Account1(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) biztype = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'account' class Contact1(models.Model): contact_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) account_id = models.ForeignKey(Account1, models.DO_NOTHING, db_column='account_id', blank=False, null=False) contact_notes = models.TextField(blank=True, null=True) contact_email = models.CharField(max_length=255, blank=True, null=True) contact_phone = models.CharField(max_length=255, blank=True, null=True) contact_status = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'contact' class Contactdeal(models.Model): contactdeal_id = models.AutoField(primary_key=True) contactdeal_deal_fk = models.ForeignKey('Deal', models.DO_NOTHING, db_column='contactdeal_deal_fk', blank=True, null=True) contactdeal_contact_fk = models.ForeignKey(Contact1, models.DO_NOTHING, related_name='contactdeal_contact_fk', db_column='contactdeal_contact_fk', blank=True, null=True) class Meta: managed = False db_table = 'contactdeal' class Deal(models.Model): deal_id = models.AutoField(primary_key=True) deal_name = models.CharField(max_length=255, blank=True, null=True) est_value = models.DecimalField(max_digits=13, decimal_places=2, blank=True, null=True) deal_notes … -
How to combine and load data in django like this?
this is my models class model1(models.Model): name = models.charField() class model2(models.Model): model1 = models.Foriegnkey(model1) id = models.IntegerField(primarykey=True) title = models.charFiled() I wanted some thing like this {"model_name1":[{"id":1,"title":"title1"},{"id":2,"title":"title2"}], "model_name2":[{"id":3,"title":"title1"},{"id":4,"title":"title2"}],} how to achieve this in django, the effiecient way -
unable to resolv didn't return an HttpResponse object. It returned None instead
If no input in search bar it returns me the folowing The view wish.views.create_wish didn't return an HttpResponse object. It returned None instead. def create_wish(request): if request.method == 'POST': form = WishForm(request.POST) if form.is_valid(): wish = form.save(commit=False) wish.author = request.user wish.save() my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) messages.success(request, ( "Your location that you want to " "visit has been added to List !")) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) else: my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) I just want to go back to the page with a message " please enter a place" -
Django Api url conflicting whenever i apply the url of the app into the urlpatterns and i don't know the way forword here
So, whenever i add this path('api/', include('api.urls')) into the parent urls i get a bunch of errors in the terminal and if i remove it from the urlpatterns i get page not found wheni reload the localhost on my browser, and on the terminal page it shows "Broken pipe from ('127.0.0.1', 8441)" and i'm really really confused right now. Api urls from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('users', views.UserViewSet, basename='user') urlpatterns = router.urls Parent Urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('api.urls')) ] Errors C:\Users\Administrator\Desktop\CRUD\songcrud\api\views.py changed, reloading. Performing system checks... System check identified no issues (0 silenced). November 07, 2022 - 01:32:32 Django version 4.1.3, using settings 'songcrud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [07/Nov/2022 01:32:47] "GET / HTTP/1.1" 404 2170 Not Found: /favicon.ico [07/Nov/2022 01:32:47,092] - Broken pipe from ('127.0.0.1', 8441) C:\Users\Administrator\Desktop\CRUD\songcrud\songcrud\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\Desktop\CRUD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, … -
CrateDB as timeseries database for Django
I am trying to use CrateDB as timeseries database for Django. I am deploying both services on docker for development. I started by deploying the following versions: Django: 4.1.3 CrateDB: 5.1.0 However, I was getting compatibility error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.5). I have downgraded the Django version to 3.0 where I don't get that error, however now I get this one: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InternalError_: Unknown function: pg_catalog.pg_table_is_visible(c.oid) CONTEXT: io.crate.exceptions.SQLExceptions.esToCrateException(SQLExceptions.java:164) io.crate.exceptions.SQLExceptions.prepareForClientTransmission(SQLExceptions.java:151) io.crate.protocols.postgres.Messages.sendErrorResponse(Messages.java:190) io.crate.protocols.postgres.PostgresWireProtocol.handleSingleQuery(PostgresWireProtocol.java:795) io.crate.protocols.postgres.PostgresWireProtocol.lambda$handleSimpleQuery$3(PostgresWireProtocol.java:748) java.base/java.util.concurrent.CompletableFuture.uniComposeStage(CompletableFuture.java:1187) java.base/java.util.concurrent.CompletableFuture.thenCompose(CompletableFuture.java:2309) io.crate.protocols.postgres.PostgresWireProtocol.handleSimpleQuery(PostgresWireProtocol.java:748) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchMessage(PostgresWireProtocol.java:335) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchState(PostgresWireProtocol.java:325) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:293) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:277) io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:336) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:308) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in … -
Dajngo Channels - synchronousonlyoperation is thrown when using SessionMiddlewareStack
I am trying to implement anonymous chat using Django Channels for websocket connection. However, i keep getting the SynchronousOnlyOperation exception when using SessionMiddlewareStack for authentication. Python version: 3.8 Django Version: 4.1 Channels version: 3.0.5 Consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import * class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def add_user_to_room_pool(self): former = Pool(username=self.user, room_name=self.get_room()) former.save() @database_sync_to_async def remove_user_from_room_pool(self): former = Pool.objects.filter(username=self.user, room_name=self.get_room()) former.delete() async def connect(self): self.room_id = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_id self.user = self.scope['session']['Anonymous-Name'] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.add_user_to_room_pool() await self.accept() async def disconnect(self, close_code): await self.remove_user_from_room_pool() await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.create_message(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, } ) @database_sync_to_async def get_room(self): return Room.objects.get(name=self.room_id) @database_sync_to_async def get_user(self): return Hikka.objects.get(user=self.scope['user'].id) @database_sync_to_async def create_message(self, text): former = Message(message_author=self.user, message_room=self.get_room(), message_text=text) former.save() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) I've tried removing all cached session data from both Django and web-browser, but that didn't help. I've seen custom implementation of the Middleware, that uses token authentication, but that's not what i need. What i need is to be able to use self.scope['session'] in order … -
File upload button
I would like to have a file upload button for a models.ImageField. However, I don't want it to render with choose file:no file chosen. Instead, I would like a file upload button that pops up a select file button. Is this possible? -
Hi need a solution
I have deployed to post g res p g admin4 and deleted db. s q lite from Django. and set my allowed host =['*'] Am getting server [500]. if any help will be appreciated need a solution after deleting s q .lite d b from Django project and used allowed host to * . am getting 500 server request. LOOKING FOR SOLUTION AM NEW TO DJANGO -
How to add field variables from the HomePage to a stream StructBlock
Hi i have a doubt around how can i show info from the model page onto a block, specifically, a structblock. On my homepage model i have multiple charfields, where i store the link of the social media of the website, and i wish to know how can i print these links inside the template of a structblock on my streams, additionally i wish to know if this is possible too for an img, this is what i've tried so far: home/models.py class HomePage(Page): template = "home/home_page.html" landing_page_template = "home/home_page.html" social_media_display = BooleanField(blank=True, default=True) facebook_link = CharField(max_length=200, default="#") instagram_link = CharField(max_length=200, default="#") twitter_link = CharField(max_length=200, default="#") youtube_link = CharField(max_length=200, default="#") logo_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) Streams/blocks.py class FooterPlus(blocks.StructBlock): tlf = blocks.CharBlock(required=True, max_length=20, label="Tlf", default="+58") email = blocks.CharBlock(required=True, max_length=20, label="Email", default="") class Meta: template = "streams/parts/footer_plus.html" icon = "plus" label = "Footer plus" footer_plus.html <a href="{{self.facebook_link}}" class="list-group-item list-group-item-action"></a> -
how to get the foreignkey attribute value
I'm trying to print out the email related to a specific OrderItem for a Customer, even tho the email exists, it returns "None" instead, what part of my logic is wrong? #Models class Customer(models.Model): email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): #View def test(): try: customer_email = OrderItem.objects.get(order__customer__email=['email']) except OrderItem.DoesNotExist: customer_email = None print(customer_email) -
Use Django Rest API to verify emails for new users in Flutter
We have made the email verification API thru Django, how do I implement it in Flutter? There are many tutorials using Firebase, but not many using Django. Thanks! I am expecting to use Django to send a verification email when a new user register an account -
Is it possible to send data from one form to multiple models in django using a normal form instead of multiple ModelForm?
I know it sounds weird, but I'm struggling a lot to show multiple tables with an inline, which populates three models with foreign keys, so I'm trying to find easier solutions than creating a script with JavaScript (which I don't know how to do) or a very complicated solution. My idea is to create a normal form with all of the fields and use it to fill all the models. class Order(models.Model): customer = models.ForeignKey("Customer", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ("-created",) def get_absolute_url(self): return reverse("sales:order-update", kwargs={"pk": self.pk}) def __str__(self): return "Order {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey( Product, related_name="order_items", on_delete=models.CASCADE ) quantity = models.PositiveIntegerField(default=1) def __str__(self): return "{}".format(self.id) def get_cost(self): return self.price * self.quantity class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=15, null=True) email = models.EmailField() address_line_1 = models.CharField(max_length=250) address_line_2 = models.CharField(max_length=60, null=True) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) state = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, default="Mexico") def __str__(self): return f"{self.first_name} {self.last_name}" def get_absolute_url(self): return reverse("sales:modalcustomercreation") I only tried the first solution in [this stackoverflow question](https://stackoverflow.com/questions/5720287/django-how-to-make-a-form-for-a-models-foreign-keys) but It doesn't worked. -
ReactNative, Apollo and Django: upload files
I decided to learn such a technology as GraphQL. For this, I came up with an application (I develop it on ReactNative), a python backend (django-graphene). How the client chose Apollo. I set everything up, everything works, I even did a part already. And here I needed to upload a profile photo. The problem is that I haven't found a way to do this. I used to use the REST API and the client was axios. So I just took the FormData and passed it. Accordingly, the backend accepted and saved as usual. And here I don't even know where to start. I found the apollo-upload-client package, but I didn't find how to integrate it into ReactNative (more precisely, there is a description there, but I didn't understand how to use it correctly). I do it like this: const fileSubstitute = { uri: uriFromCameraRoll, name: "a.jpg", type: "image/jpeg", }; I found graphene-file-upload for the backend, it seems to see my files, but I don't know how to save them (by the way, I can transfer the file without apollo-upload-client). I really like GraphQL, but uploading files is a big deal. If I don't solve it, I will be forced abandon … -
how can I implement AJAX when i need to return a stored procedure function result in my views.py?
Im trying to implement ajax with a django app, specially with a view where I call a stored procedure to return a result -
Django, different result between `all()` method and `all().values()` method
I am facing this problem, where i can't access the url of some image using values() method, but it still can be accessed if it is a queryset object rather than a pythonic list: class MyModel(models.Model): img = models.ImageField(upload_to='media') # the image is stored in aws, hence it will produce a url def __str__(self): return f"{self.img.url}" this is example model, now let's try printing that on the shell: >>models.MyModel.objects.all() <QuerySet[{'img':'https://aws/bucketlist.com/some_img.png'}]> however with values() method: >>models.MyModel.objects.all().values() <QuerySet[{'img':'media/some_img.png'}]> ``` as you can see with `values()` i get the local path rather than the url to the aws cloud note that aws storage is set correctly in django. settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = "/media" AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = "ap-southeast-2" AWS_S3_ADDRESSING_STYLE = "virtual" however, images are appearing on AWS and it seem to be fine on the cloud side. -
Alternatif to CSRF in Django
I run an Django app inside an iframe which is with php hosted on another server. All works except the POST request, I got error in Firefox only: Request failed with status code 403 > CSRF verification failed > CSRF cookie not set Previously i had Sameside warning which i solved by allowing Samesite secure in php script: PHP: ini_set('session.cookie_httponly',1); ini_set('session.use_only_cookies',1); $cookieParams = session_get_cookie_params(); $cookieParams[samesite] = "None"; $cookieParams[secure] = true; session_set_cookie_params($cookieParams); session_start(); Warning gone but sill cookie not passing over iframe, but present in Chrome. So i think i could skip the cookie then send it via Axios because i use Axios to send the request: JS: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; const config = { headers: { 'method':'POST', 'accept': '*/*', 'content-type': 'application/json;charset=UTF-8', withCredentials: true, 'X-CSRFTOKEN': window.csrf_token, //csrfmiddlewaretoken: window.csrf_token } }; axios.post(url, datas, config).then((res) => {.... Settings.py: CSRF_TRUSTED_ORIGINS = ['https://myPhpsite.com', 'myPhpsite.com'] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOW_CREDENTIALS = True After tying many things i'm thinking to disable the csrf by commenting 'django.middleware.csrf.CsrfViewMiddleware',. If I do it, is it an alternatif to csrf in order to get protected like csrf provide? -
How to design a database to make correction documents for sales invoices
How (simplified) to design a database/models to make correction documents for sales invoices? class Product(models.Model): title = models.CharField(max_length=50) class Invoice(models.Model): title = models.CharField(max_length=50) class InvoiceItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=5, decimal_places=2) class InvoiceCorrectionNote(models.Model): document = models.ForeignKey(Invoice, on_delete=models.CASCADE) class InvoiceCorrectionItem(models.Model): item = models.ForeignKey(InvoiceItem, on_delete=models.CASCADE) document = models.ForeignKey(InvoiceCorrectionNote, on_delete=models.CASCADE) original_quantity = models.DecimalField(max_digits=5, decimal_places=2) quantity_after_correction = models.DecimalField(max_digits=5, decimal_places=2) -
Attempting to read pk from url in django, but getting error NoReverseMatch at /
I am attempting to insert a link into my navbar (header.html - which is included in my base.html) which leads to the users profile. In order to provide the profile of the user who is currently logged in, I am attempting to use a primary key via the url. However, I am receiving the following error message: Reverse for 'url' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['profiles/show/(?P[0-9]+)/\Z'] I have a Profile model defined (shown below) with a OneToOne Relationship to my User model. I am wondering if I am trying to parse in the wrong pk reference in my header.html file. If so I think the issue will be on line 17 "Show Profile", but may also be in my view file? Something is definitely going wrong with my primary key, but am new to Django and cant work out what it is! Model: class Profile(models.Model): # Get access to create profile by default MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, …