Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
use *args in django url paramater
I have a webpage within my site which shows a list of Lego set themes. Each theme may have sub-themes and those sub-themes may also have sub themes. In the image below each indentation level represents what themes are sub-themes of other themes. For example on my page a user could take the path: http://127.0.0.1:8000/themes (shows all parent themes) http://127.0.0.1:8000/themes/train (shows all sub themes of train) http://127.0.0.1:8000/themes/train/9V (shows all sub themes of train/9V) http://127.0.0.1:8000/themes/train/9V/My%20Own%20Train (no sub themes) In my view i suppose i would use *theme to handle any number of sub-themes url path http://127.0.0.1:8000/theme/train/9V/ views.py def theme(request, *theme): #theme = ('train', '9V') theme_path = "".join([theme + "/" for theme in themes]) #theme = 'train/9V/' theme_items = db.get_theme_items(theme_path) sub_themes = db.get_sub_themes(theme_path) context = { "parent_theme":theme[0], "theme_items":theme_items, "sub_themes":sub_themes, } return render(request, "App/theme.html", context=context) urls.py urlpatterns = [ ... path('theme/<str:theme_path>', views.theme, name="theme"), ... ] theme.html sub_theme.0 = name of the sub theme e.g '9V' sub_theme.1 = image url header = parent to sub theme e.g 'train' {% for sub_theme in sub_themes %} <div class="theme-container"> <p><a href="{% url 'theme' parent_theme %}/{{sub_theme.0}}">{{sub_theme.0}}</a></p> <img src="{{sub_theme.1}}" alt="{{sub_theme.0}}_url"> </div> {% endfor %} How could i pass multiple parameters into the url which can be handled by my … -
Django & Digital Ocean: Exception("DATABASE_URL environment variable not defined") When running local server
I built a django app on my local machine, and then used this tutorial to deploy it with app platform (https://docs.digitalocean.com/tutorials/app-deploy-django-app/) The deployment was successful. However, now when I try to run my django app locally to continue development, I’m getting the following error: …/settings.py", line 95, in raise Exception(“DATABASE_URL environment variable not defined”) Exception: DATABASE_URL environment variable not defined Current settings in settings.py: DEVELOPMENT_MODE = os.getenv(“DEVELOPMENT_MODE”, “False”) == “True” DEBUG = os.getenv(“DEBUG”, “False”) == “True” I am unsure of how to reset my settings.py file so that it points to a local sqlite3 db for development. -
Static files not loading
I'm trying to create an homepage for my app but my page keeps loading after adding the STATIC_ROOT and STATICFILES_DIR. it gives Broken pipe from ('127.0.0.1', 49634) in my terminal. This is my home.html This is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') this is my urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to update FileField or ImageField hosted by s3 in my Django project?
I have a Django web app that allows users to upload a picture or video, and it works perfectly when I upload it the first time, but when I go back to change it, it doesnt update, it allows me to to clear the field but I can't upload a new file. I'm totally new to s3 and am having a hard time reading the docs. I'm not sure what code I should attach, but this is in my settings.py AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can also share my views.py but I feel like it has something to do with permissions. Any help would be greatly appreciated! -
Django return a ManyToMany field from other class
I have two classes in django: class MovementsGyn(models.Model): gyn_name = models.CharField('Name', max_length=70) gyn_desc = models.TextField('Description', blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] class Rod(models.Model): Rod_name = models.CharField('Rod Name', max_length=70) movements_gym = models.ManyToManyField(MovementsGyn) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] And a view to show the result grouped: def estatistica(request): template = 'moviment.html' estatic_movem_gyn = Rod.objects.filter(owner=request.user) \ .values('movements_gym').order_by('movements_gym') \ .annotate(qtde=Count('id')) context = { 'estatic_movem_gyn' : estatic_movem_gyn } return render(request, template_name, context) The result is movements_gym grouped and, in qtde, the quantity of register that we have in database. The question is, how can I show the field gyn_name that are in MovementsGyn models ? -
Receiving Error: 'apxs' command appears not to be installed
This is the error I am receiving: RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. How can I get around this? I have received this while trying to install different packages. I am working on a Django project. I have already made sure the apache2-dev package is installed. -
Why does request.POST always contains name of the button? How to avoid it?
This is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> <script src="{% static 'jquery.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button name="button1">button1</button> <button name="button2">button2</button> <input type="text" name="textbox"> </form> </body> </html> Every time I type some text in the textbox, let's say I type: "hi" and hit enter, the request.POST returns: <QueryDict: {'csrfmiddlewaretoken': ['FX1qFNzbQUX3fYzAwW27cOu83omLzifnlLU5X0WXXVdOiyNretM5b3VgsGy1OogA'], 'button1': [''], 'textbox': ['hi']}> Why does request.POST contain 'button1': [''] even though I haven't clicked on it? Is there a way to avoid request.POST to have 'button1': ['']? -
Use multiple workspaces containing django without PYTHONPATH
Sometimes I need to run our project with django backand in multiple workspaces on different git versions. While doing it I discovered that django is heavely relying on PYTHONPATH and probably because of that mixing up the workspaces. When I call python manger.py runserver for example, I can see sources being pulled from the other workspace. On contrary, if I remove both workspaces from PYTHONPATH (which was the only thing in there) the above command fails with the quite infamous error: File "/opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: XYZ For me it looks like, he can not find the modules outside django, which has been otherwise obtained from the PYTHONPATH path. Since all our modules including the one that is reported to be missing are on the same level as django I tried to extend the sys.path in manage.py like this: import pathlib def main(): current_dir = pathlib.Path().resolve() [sys.path.append(str(x)) for x in current_dir.parent.iterdir() if x.is_dir() and not x.name.startswith(".")] Although I can see the path being extended the above exception still occurs. Any help on … -
How to customize image toolbar in ckeditor and enable Upload outside admin panel?
The first problem: If click on the image toolbar, the wizard appears with additional settings. Can I modify it to upload the image in one click without entering additional information and sending the image to the server? The second problem: Outside the admin panel, there is no upload tab on the image toolbar. How to fix it? Thanks for your time. -
Django with DRF. Users cannot sign in with their credentials
I have a web app using Django as the backend and React as the frontend. I have a sign up form where the users enter their credentials and the profile is created in the database. However, when the users create their profile, they are unable to login even though the user data is available in the database. Altering the user password with the django-admin panel fixes this issue and the users can login sucessfully into their accounts. I'm assuming this is an issue with the password saving during profile creation but I can find the issue. Profile creation method # Create user @api_view(['POST']) def sign_up(req): serializer = UserSerializer(data=req.data) if serializer.is_valid(): if User.objects.filter(email=serializer.validated_data['email']).exists(): return Response({'email': 'The email entered is already in use by another account.'}) serializer.save() return Response({'status': 'success'}) else: return Response(serializer.errors) User sign in method # Sign in user @api_view(['POST']) def sign_in(req): username = req.data['username'] password = req.data['password'] user = authenticate(req, username=username, password=password) if user is not None: return Response({'status': 'success'}) else: return Response({'err': 'The username or password entered is incorrect.\nThe username and password are case sensitive.'}) I have tried forcefully resaving the password on profile creation but that doesn't work. Have also tried some online solutions but to no … -
How to pull information from html and use it in a view in Django
Im trying to send a post request with a payload that includes a username and password. The post request works fine on its own but I'm not sure how to get the user and pass that are entered and use them with the post request. Trying to take the data entered into the html and use it in a view I've looked around online and found something suggesting something similar to which doesn't fail but instead returns none: username = response.GET.get['username'] password = response.GET.get['password'] I see this stack overflow:Django request.POST.get() returns None that definitely has the correct answer in it but I don't quite understand whats going on/what I need to do in order to get the result im trying for. I can see its something to do with that I have to post the data to the url or something for it to be eligible to grab from the above statements or something, but again, I don't really understand whats happening. Honestly what im looking for here is an ELI5 of the answer from the link -
Django-Debug-Toolbar doesn't appear
I am trying a lot to appear Debug-tool but it doesn't appear. First I install it using pipenv: pipenv install django-debug-toolbar Here settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "BookListAPI", "debug_toolbar", # added debug-tool here ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'debug_toolbar.middleware.DebugToolbarMiddleware', # added debug_toolbar.middleware ] # added INTERNAL_IPS INTERNAL_IPS = [ '127.0.0.1', ] urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include('BookListAPI.urls')), path("__debug__/", include('debug_toolbar.urls')), ] I don't know why debug-tool doesn't appear. -
Can I get some assistance with a Django/SQLite3 schema?
I am trying to put together a Django app that will show the teams and games for my fantasy football league. I have taken a few cracks at the models, but I can't get my head wrapped around how they will relate. This is what I am trying to accomplish: Each year, there are six teams that make the "Toilet Bowl" tournament, which will crown the worst team in the league. There are three rounds. The worst two teams are not playing the first round. That leaves team 1 playing team 4 and team 2 playing team 3. In round 2, teams 1 and 2 play the losers from round 1. In round 3, the remaining two teams play for the title. These are the models that I have so far. I know that they're not optimal. class Owner(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=100) phone = models.CharField(max_length=12, null=True) def __str__(self): return "%s" % (self.name) class Team(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class Game(models.Model): year = models.SmallIntegerField( validators=[MinValueValidator(2010), MaxValueValidator(2999), RegexValidator("^(20)([1-5][0-9])$") ]) round = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(3)]) teams = models.ManyToManyField(Team) #teams = models.ForeignKey(Team, on_delete=models.CASCADE) #team1_score = models.IntegerField(default=0) #team2_id = models.ForeignKey(Team, on_delete=models.CASCADE) #team2_score = models.IntegerField(default=0) def … -
Django Rest Framework + SimpleJWT returns 401 on unprotected routes
I have configured DRF to use JWT as an authentication scheme and for the most part works correctly however when a user's token & refresh token are no longer valid rather than returning a 200 as an unauthorized user for unprotected routes and displaying the website as if they are no longer logged in the backend returns a 401. I am new to the Django auth scheme / middleware setup but my assumption would be that if the default is AllowAny then a bad token would be ignored. Is there a configuration that I am missing. From the DRF Docs If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] my settings.py REST_FRAMEWORK = { ... "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": datetime.timedelta(minutes=15), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=2), ... } Example ViewSet that returns 401 with bad access token class PromoApiSet(ViewSet): serializer_class = PromoSerializer def get_queryset(self, *args, **kwargs): time_now = timezone.now() return PromoNotification.objects.filter( end_date__gte=time_now, start_date__lte=time_now ) # @method_decorator(cache_page(120)) def list(self, request): promos = self.get_queryset() serializer = self.serializer_class(promos, many=True) promos_data = serializer.data response_data = {"promos": promos_data} return Response(response_data) -
Filtering broadcasts by date and category at the same time
I am developing a Django website and faced the following problem: I need to filter broadcasts by date (the date is specified by the user) and category. Screenshot: https://i.stack.imgur.com/5V1Or.png Could you tell me how to implement such a thing shown in the screenshot? Attempts to form a get request with parameters were unsuccessful -
change in fonts and spacing in a django app
I installed django bootstrap5 but it seems to have messed up the css and fonts and i can't seem to figure out what went wrong..I have a website am trying to clone, innitially things looked pretty the same until i tried installing django bootstrap and django tailwinds, well i later uninstalled tailwinds but the mess is still there. here is the pic of the changesThe current changes in the interface Here is what it looked like innitially and how the website itself looks like website fonts -
Query with a variable
I would like to execute a query with a variable I tried to do this but it doesn't work def requeteDB(sql_request): with connection.cursor() as cursor: cursor.execute(sql_request) row = cursor.fetchall() return row def queryWithVar(): var = 'something with spaces' return(''' Select col1 From table1 Where col2 = %s ''', [var]) queryWithVar() ('\n Select col1\n From table1\n Where col2 = %s\n ', ['something']) requeteDB(queryWithVar()) TypeError: argument 1 must be a string or unicode object: got tuple instead -
How to use a list in a raw django SQL query that uses `WHERE ... IN (...)`?
How do you inject a list parameter into a Django raw query? Given a list of UUIDs i'd like to be able to inject them into the () in a WHERE ... IN (...) query. list_of_uuids = [ "<UUID_1>", "<UUID_2> ] Output for SQL: SELECT * FROM some_model_table WHERE some_model_table.uuid IN ( "<UUID_1>", "<UUID_2>" ) So I tried doing the following using raw django queries: query_set = SomeModel.objects.raw("SELECT * FROM some_model_table where some_model_table.uuid IN %s", [list_of_uuids]) Unfortunately, the above will give the following error: django.db.utils.ProgrammingError: syntax error at or near "ARRAY": LINE X: WHERE uuid IN ARRAY['00123... Which means the list is interpreted as an array and passed to the SQL query as an array, which cannot be used in an IN query. Enclosing the injected array in () also doesn't work: LINE X: WHERE uuid IN IN (ARRAY['00123... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Note: I'm aware this particular example can be done with Django ORM, but my actual query is more complex than this and has to be done with raw queries, and contains this WHERE ... IN (...) syntax. I just kept the irrelevant … -
i cant display url tag in template
views.py ` def Product_details (request , product_name): product_detail = Product.objects.get(pk=product_name) return render (request, 'product_detail.html', { 'product_detail' : product_detail, }) ` urls.py ` urlpatterns = [ path('', views.Product_list , name= 'Product_list'), path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), product_detail.html ` <a href="{% url 'Product_details' product.name %} `` display url tag in page -
Pandas Converts My date string value in date column to an integer
I have an excel file which I am using pd.read_excel() to read, inside the excel file are couple of date columns (the date data type is a string and must follow this format: dd/mm/yyyy. The problem I have is that when the excel file gets converted to a dataframe using pd.read_excel(), the values gets converted into an integer. Does anyone know how I can maintain the value in the excel file after it has been converted to a dataframe. Screenshot below: The columns with the date format What the values get converted to after converting the file to a dataframe "43800" is what the value of "Incorporation Date" got converted to. What I have tried: for column in columns_with_date_string: client_entity_df[column] = pd.to_datetime( client_entity_df[column].astype(int) ) client_entity_df[column] = client_entity_df[column].dt.strftime('%d/%m/%Y') This approach returned the values as "01/01/1970", instead of the dates specified TLDR: I basically want to maintain the value of my date columns (12/11/2022) in my excel file where the format is "dd/mm/yyy" when the excel file gets converted to a dataframe, pandas currently changes the values to an integer (which I assume is an epoch) when it converts the file to an integer. -
The Django serializer for MongoDB does not display data correctly
So, I have 2 models, Flow and Steps. I want that when the Flows are displayed, the steps corresponding to this flow should also be displayed, something that doesn't happen even though it should. (I want to specify that before switching to Mongo, I was using another library for the serializer and everything was working perfectly, now not, and I need it this way) Flow Model: class Flow(BaseModel): class BrowserInstance(Enum): CHROME = 'chrome' FIREFOX = 'firefox' name = StringField() url = URLField() browser = StringField(choices=list(item.value for item in BrowserInstance), default=BrowserInstance.CHROME.value) scheduling = StringField() next_schedule = DateTimeField(default=timezone.now, null=True) is_active = BooleanField(default=False) user = ReferenceField(User, reverse_delete_rule=CASCADE, null=False) Step model: class Step(BaseModel): class Action(Enum): CLICK = 'click' TAPPING = 'tapping' SUBMIT = 'submit' CLEAR = 'clear' ENTER = 'enter' step_number = IntField() action = StringField(choices=list(item.value for item in Action), default=Action.CLICK.value) selector_xpath = StringField(max_length=254) content = StringField(max_length=254, blank=True) flow = ReferenceField(Flow, reverse_delete_rule=CASCADE, related_name='steps') Step Serializer class StepSerializer(DocumentSerializer): class Meta: pattern = Step fields = ('id', 'step_number', 'action', 'selector_xpath', 'content') FlowSerializer class FlowSerializer(DocumentSerializer): steps = StepSerializer(many=True, required=False, allow_null=True) class Meta: model = Flow fields = "__all__" When I execute the get / retrieve endpoint, next to the steps I receive the value null (if I … -
how to set relevent foreign key django in form
I want to submit video in section wise. i create section.When i want create a video i want to set my course name by default and want to show relevent section. Course class Course(models.Model): instructor = models.ForeignKey(UserProfile,on_delete=models.CASCADE) name = models.CharField(max_length = 50 , null = False,unique = True) slug = models.CharField(max_length = 50 , null = False , unique = True) Section: class SectionVideo(models.Model): course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE) name = models.CharField(max_length = 50 , null = False) slug = models.CharField(max_length = 50 , null = False ) serial_number = models.IntegerField(null=False) video: class Video(models.Model): section_video = models.ForeignKey(SectionVideo , null = False , on_delete = models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete = models.CASCADE) title = models.CharField(max_length = 100 , null = False) video_description = models.CharField(max_length = 500 , null = True) how i will make my create-form for videos. -
Django: Filter matching objects using 2 fields
Sorry if the title is not very telling I have the following classes: class Event(Model): ... class IOCType(Model): name = CharField(max_length=50) class IOCInfo(Model): event = ForeignKey(Event, on_delete=CASCADE, related_name="iocs" ioc_type = ForeignKey(IOCType, on_delete=CASCADE) value = CharField(max_lenght=50) Each event has one or several IOCs associated with it, which are stored in the IOCInfo table. This is how my IOCInfo table looks like after creating some events: id value event_id ioc_type_id 1 some-value1 eventid1 4 2 some-value2 eventid1 8 3 some-value3 eventid1 8 4 some-value4 eventid1 1 5 some-value3 eventid2 8 6 some-value1 eventid2 1 7 some-value2 eventid3 8 8 some-value3 eventid4 8 What I want to do is to take an event, compare its IOCInfo with those of other events and get back those events that match. This is what I have done so far and it works, but I fear that as the database grows and the app has more users this query will end up being a bottleneck def search_matches(event): matches = Event.objects.none() for ioc in event.iocs.all(): matches |= Event.objects.filter( iocs__ioc_type=ioc.ioc_type, iocs__value=ioc.value ) return matches.exclude(event=event.id) If I pass the eventid2 to The above function, it will return eventid1 and eventid4 as expected. Any suggestions to improve this function using any … -
Django Channels AsyncWebSocketConsumer ConnectionClosedError 1005
I am writing a django channels application and noticed an exception when handling a heartbeat function related to websocket status code which I haven't been able to find any existing issues for. This is in an AsyncWebsocketConsumer backed by redis. ConnectionClosedError: websockets.exceptions.ConnectionClosedError: received 1005 (no status code [internal]); then sent 1005 (no status code [internal]) async def receive(self, text_data): try: if text_data == "healthcheck": await self.send( text_data=json.dumps({"type": "healthcheck", "data": self.group_name}) ) else: logger.info(f"Unsupported WS Event: {text_data}") pass except: logger.exception("Failed to handle message from client") Also receive this error RuntimeError: RuntimeError: Unexpected ASGI message 'websocket.send', after sending 'websocket.close'. My disconnect implementation is async def disconnect(self, close_code): try: # Leave room group await self.channel_layer.group_discard(self.group_name, self.channel_name) await self.log_request("disconnect") except: logger.exception("Failed to disconnect user from socket") -
In DRF, how to get dictionary format in JSON response rather than List of dcitionaries
How to get dictionary format in JSON response rather than List of dictionaries. Right now am getting response like list of dictionaries and I want to get response without list. #Response I get for example [ { "id": 40, "full_name": "Don Ser 1", "email": "Donny@sfds.com", "phone": 12345, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", }, { "id": 41, "full_name": "Don Ser 2", "email": "Donny@sfds.com", "phone": 121356456, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", } ] #Response I Like to get is without List. [ { "id": 40, "full_name": "Don Ser 1", "email": "Donny@sfds.com", "phone": 12345, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", }, { "id": 41, "full_name": "Don Ser 2", "email": "Donny@sfds.com", "phone": 121356456, "address_line_1": "sdsdsdsd", "address_line_2": "dsdsdsd", } } How do I achieve this? Additionally I like to know why it returned it in List rather than dictionary?