Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to persist sqlite3 db in project folder when using Docker
I have a small project that me and another person are working on. The application is gathering some data and stores it in a sqlite db (located in ./data/db.sqlite3 ) that we want to keep and exchange through our git repo along with all the rest of the project code. When I try to dockerize the app, sure on each of our machines the data persists, yet not in the project folder itself. This is the docker-compose.yml: version: "3.8" services: gcs: build: . volumes: - type: bind source: ./data target: /data ports: - "8000:8000" And here is the Dockerfile itself: FROM python:3.8-slim-buster WORKDIR /gcs COPY requirements.txt requirements.txt RUN apt-get update && apt-get install nginx vim binutils libproj-dev gdal-bin -y --no-install-recommends RUN pip3 install -r requirements.txt COPY . . CMD python3 manage.py runserver 0.0.0.0:8000 Somehow I would say that the above mounts the 'data' folder in our projects folder to a data folder in the container. When I use docker inspect to see what's up there - it all seems fine, the source folder perfectly corresponds with my project db location: "Mounts": [ { "Type": "bind", "Source": "/Users/rleblon/projects/gcsproject/data", "Destination": "/data", "Mode": "", "RW": true, "Propagation": "rprivate" } Yet somehow the persistent … -
for message in messages: TypeError: 'Messages' object is not iterable
Am having issues with looping through an object here is my code from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Messages.last_30_messages() content = { 'messages': self.messages_to_json(messages) } self.send_chat_message(content) def new_messages(self, data): sender = data['from'] author_user = User.objects.filter(username=sender)[0] message = Messages.objects.create(sender=author_user, msg=data['message']) content = { 'command': 'new_messages', 'message': self.messages_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'msg': message.msg, 'timestamp': str(message.timestamp) } command = { 'fetch_messages': fetch_messages, 'new_messages': new_messages } def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_link"] self.room_group_name = "chat_%s" % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.command[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": "chat_message", "message": message, } ) def send_message(self, massage): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event["message"] self.send(text_data=json.dumps(message)) -
Error when django import rpy2 but OK with single python file (NotImplementedError)
import rpy2.robjects as robjects import rpy2.robjects.packages as rpackages from rpy2.robjects.vectors import StrVector packageNames = ('afex', 'emmeans') utils = rpackages.importr('utils') utils.chooseCRANmirror(ind=1) packnames_to_install = [x for x in packageNames if not rpackages.isinstalled(x)] # Running R in Python example installing packages: if len(packnames_to_install) > 0: utils.install_packages(StrVector(packnames_to_install)) data = robjects.r('read.table(file ="R.appendix3.data", header = T)') data.head() afex = rpackages.importr('afex') model = afex.aov_ez('Subject', 'Recall', data, within='Valence') emmeans = rpackages.importr('emmeans', robject_translations={"recover.data.call": "recover_data_call1"}) pairwise = emmeans.emmeans(model, "Valence", contr="pairwise", adjust="holm") print(pairwise) The python file imports rpy2 to use the function of r package. It's OK, but an error is occured in the Django framework (same code). NotImplementedError at /myapp/test/ Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>' What can I do to prevent it from happening? I want to implement the r package on the web under django.Thanks so much. -
Django doesn't render validation error of custom form validator
So I have the following form class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={ 'class': tailwind_class })) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) company_id = forms.CharField(label='Company Identifier', widget=forms.PasswordInput(attrs={'class': tailwind_class})) class Meta: model = get_user_model() fields = ('email', 'password1', 'password2', 'company_id') # Custom validator for the company id def clean_company_id(self): company_id = self.cleaned_data['company_id'] if not Company.objects.get(id=company_id): raise ValidationError("This Company ID doesn't exist") # Return value to use as cleaned data return company_id whose validator works except of displaying the error message in case it doesn't validate. That's my template: <form class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-woys-purple rounded-lg text-white" method="post" action="."> {% csrf_token %} <div class="error-wrapper mb-2"> <div class="errors text-woys-error-light text-center">{{ form.errors.email }}</div> <div class="errors text-woys-error-light text-center">{{ form.errors.password2 }}</div> <div class="errors text-woys-error-light text-center">{{ form.non_field_errors }}</div> </div> ... -
Django superuser not allowed to edit this model
Since recently I need to work home, but Django is working against me. I'm having a very peculier issue. I clone the repo, create a MySQL schema, migrate, dump all the data from the server into my local db so I have something to work with, start the server and I log in as the superuser. Now this is basically a job vacancy app for our company. These are my models: Status Department Location Contactperson Vacancy Applicant I can edit entries for anything not related to a department, which are statuses, locations or contacts. But when it comes to the rest, I get a error messsage saying my user is not allowed to edit these. An applicant is related to a vacancy which is related to a department, so I get the error message at all of these. class DepartmentAdminForm(ModelForm): prepopulated_fields = {'slug': ('name',)} readonly_fields = ['banner_image', 'button_background_image_location'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.obj = kwargs.pop('obj', None) super(DepartmentAdminForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() if self.instance.pk is None: # add return cleaned_data cleaned_data = super().clean() user = self.request.user is_authorized = department_role_check(self.obj, user) if is_authorized: return cleaned_data else: raise forms.ValidationError('You are not allowed to edit this department.') … -
Django authentication no longer works over HTTPS with custom domain
I have a django app deployed in a docker container in an azure appservice. It works fine on the provided URL: https://xxxx.azurewebsites.net I then set up a custom domain through azure using a cname xxxx.mysite.com. I verified the domain, and then purchased an SSL cert through azure and bound it to my custom domain. Now the app pulls up to the login screen, but authentication fails. I am not sure what I am missing. I also cannot figure out how to access any HTTP or nginx logs with in the app service. docker-compose.yml version: '3.4' services: myapp: image: myapp build: context: . dockerfile: ./Dockerfile ports: - 8000:8000 - 443:443 Dockerfile # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.9-buster EXPOSE 8080 EXPOSE 443 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements RUN pip install mysqlclient COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos … -
Just updated to Django 4.0 and getting CSRF errors
What is the issue here. I have just updated to django 4 and on prodduction I am getting 403 csrf errors: Here are my settings: ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', "https://exactestate.com", 'app', # '.ngrok.io' ] # '.ngrok.io', 'app' ALLOWED_ORIGINS = ['http://*', 'https://*'] CSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy() The error is simply: Origin checking failed - https://exactestate.com does not match any trusted origins. -
Same FilterSet acts differently in two places
I use the same filterset_class for filtering results in FE, and for excel report generation. In FE everything works well, results are filtered correctly, buit for excel generation, the period filter is not applied. While debugging I see the period filters is available in the filter_args (see comment in bottom code block), but are not applied: count(logs) should be 1, but is 17. So something happens between declaring filter_args and logs in get_serialized_data, but have not been able to figure out what. Any ideas? views.py class LogFilterSet(FilterSet): model_names = [t.target_class._meta.model_name for t in ALLOWED_SELECTION_TARGET_MODELS] employee = NumberFilter(field_name="owner__id") company = NumberFilter(field_name="owner_company__id") period = CustomIsoDateTimeRangeFilter(field_name="start") class LogViewSet(viewsets.ModelViewSet): queryset = Log.objects.prefetch_related("selections").reverse().with_add_data() serializer_class = LogSerializer filter_backends = (DjangoFilterBackend,) filterset_class = LogFilterSet search_fields = None def get_queryset(self): queryset = super().get_queryset() if self.action in ["list", "detail"]: return queryset.for_role(self.request.role) return queryset.writable_for_role(self.request.role) CustomIsoDateTimeRangeFilter in utils.py class CustomMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = () super().__init__(widgets, attrs) def value_from_datadict(self, data, files, name): return data.getlist(name) if isinstance(data, QueryDict) else [] class CustomIsoDateTimeRangeField(IsoDateTimeRangeField): widget = WaybillerMultiWidget class CustomIsoDateTimeRangeFilter(RangeFilter): field_class = IsoDateTimeRangeField Filtered queryset for excel generation: def get_serialized_data(self): logs = ( Log.objects.prefetch_related("selections") .for_role(self.request.role) .with_add_data() .reverse() ) if filter_args := self.request.kwargs.get("filters"): # {'period': ['2022-09-06T21:00:00.000Z', '2022-09-07T20:59:59.000Z'], 'employee': 36} _filter = LogFilterSet(data=filter_args, queryset=logs) if not … -
Missing @property functions from metaclas in my Enum, what am I doing wrong?
I don't really like an implementation detail from Django's ChoicesMeta so I wanted to create my own enum metaclass that would fix that behaviour. In essence, this is what I wrote: from django.db.models.enums import ChoicesMeta as DjangoChoicesMeta class ChoicesMeta(DjangoChoicesMeta): def __new__(metacls, classname, bases, classdict, **kwds): # Here the code to fix the behavior I don't like return super().__new__(metacls, classname, bases, classdict, **kwds) class ChoiceEnum(Enum, metaclass=ChoicesMeta): pass class SomeEnum(ChoiceEnum) ONE = "some enum value 1" TWO = "some enum value 2" But then, when I wanted to use the property .choices that comes from django.db.models.enums.ChoiceMeta, I get an AttributeError: File "/usr/lib64/python3.10/enum.py", line 437, in __getattr__ raise AttributeError(name) from None AttributeError: values even though I can access to the property .__members__ that comes from ChoiceMeta's parent EnumMeta. Cant someone tell me what I'm doing wrong? -
Having trouble using javascript to create dynamic URL's with django for dates
Currently I have two basic routes: urlpatterns = [ path('<int:tutor_id>/', views.tutorHomeOverviewPage, name='tutorHomeOverviewPage'), path('<int:tutor_id>/<str:selected_date>/', views.tutorSelectedDay, name='tutorSelectedDay'), ] These routes point to two views which just get data from the database and send it to the template. The views work without any issues. My issue seems to lie with the URL that is being created in my JS files. So I have a calendar that dynamically gets list elements from a javascript for days that look like this: <a href="2022-10-14" id="day14">14</a> When I am at the URL - http://127.0.0.1:8000/tutorhomepage/7/ (which matches the first URL path) and I click on one of the days (so let's say the anchor element above), it goes to the correct URL: http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/ However, when I click on another day while at http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/, it just adds a second date to the URL like so - http://127.0.0.1:8000/tutorhomepage/7/2022-10-14/2022-10-1 My javascript, which is creating the 'a href' links, looks like this in brief: aLink.setAttribute('href', currentYear + '-' + (currentMonth + 1) + '-' +dayCounter) Any idea why this is happening and a possible fix for it? -
mysql.connector imports through the python shell, but still throws error in python module
I have a simple python module test.py. Its content is: import mysql.connector When I run it, it gives this error: C:\xxx\Software\Website\django\Scripts\python.exe C:\xxx\Software\Website\django\MyDB\test.py Traceback (most recent call last): File "C:\xxx\Software\Website\django\MyDB\test.py", line 1, in <module> import mysql.connector ModuleNotFoundError: No module named 'mysql' Process finished with exit code 1 So it can't find mysql.connector. But when I go into the python shell (launched from the directory of test.py), running >>> import mysql.connector doesn't give any error. So the mysql.connector package must be installed, somewhere. How come running the python module gives an error, while running the same python instruction through the python shell doesn't? -
How to calculate current day streak in Django?
I would like to calculate every time a ClassAttempt with a status "completed" is created or updated. class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True) collected_xp = models.IntegerField(null=True, blank=True, default=0) status = models.CharField( verbose_name='status', max_length=20, choices=( ('no-completed', 'no-completed'), ('completed', 'completed'), ), default='no-completed' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
How to set default user password when creating users in Django?
I'm creating my first programming project with Django as part of the IB Computer Science course and I decided to make a platform where students can access their grades. I want admins to be able to create new students, with a default password that students can reset later on. After trying to researching it and read the Django docs, I found out that I have to make use of Django's AbstractBaseUser. However, after trying to watch multiple tutorials which did not answer my question, I am now stuck. Is there a way to implement this function? -
Django: Why I can't access extra fields in Many to Many relationship with _set.all in templates. What is wrong?
I want to access the extra field is_valid of Class GroupMember (ManytoMany relation with Class Group). In templates I do: {% for field in user.groupmember_set.all %}{{ field.is_valid }}<br>{% endfor %} But nothing is shown. Where is the problem? The relevant code is below models.py from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=255, unique=True) members = models.ManyToManyField(User,through="GroupMember") def __str__(self): return self.name class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_valid = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") views.py class SingleGroup(DetailView): model = Group urls.py path("groups/<pk>/",views.SingleGroup.as_view(),name="single"), template: groups/<pk> {% for field in user.groupmember_set.all %}{{ field.is_valid }}<br>{% endfor %} -
I am getting a "error": "invalid_client" on social_oauth2. When i try to get the tokens through. I am trying the tokens for DjangoOauth
I have attached the requirements.txt. I am unable to get the token even after changing versions of djangorestframework etc. Please help. I have been trying different things for 3 days. [![```appdirs==1.4.4 asgiref==3.2.10 astroid==2.4.2 autopep8==1.5.4 boto3==1.14.31 botocore==1.17.31 cachelib==0.1 certifi==2020.4.5.1 cffi==1.15.1 chardet==3.0.4 click==7.1.2 colorama==0.4.4 cryptography==38.0.1 cs50==5.0.4 defusedxml==0.7.1 Deprecated==1.2.13 distlib==0.3.1 Django==3.1.4 django-ckeditor==5.9.0 django-cors-headers==3.5.0 django-crispy-forms==1.9.2 django-filter==2.3.0 django-js-asset==1.2.2 django-oauth-toolkit==2.2.0 django-storages==1.9.1 djangorestframework==3.11.1 docutils==0.15.2 drf-social-oauth2==1.0.8 filelock==3.0.12 Flask==1.1.2 Flask-Session==0.3.2 gunicorn==20.0.4 idna==2.9 install==1.3.3 isort==5.6.4 itsdangerous==1.1.0 Jinja2==2.11.2 jmespath==0.10.0 jwcrypto==1.4.2 lazy-object-proxy==1.4.3 MarkupSafe==1.1.1 mccabe==0.6.1 oauthlib==3.2.2 Pillow==9.2.0 psycopg2-binary==2.9.4 pycodestyle==2.6.0 pycparser==2.21 PyJWT==2.5.0 pylint==2.6.0 python-dateutil==2.8.1 python-dotenv==0.13.0 python3-openid==3.2.0 pytz==2020.1 requests==2.23.0 requests-oauthlib==1.3.1 s3transfer==0.3.3 six==1.15.0 social-auth-app-django==5.0.0 social-auth-core==4.3.0 SQLAlchemy==1.3.17 sqlparse==0.3.1 termcolor==1.1.0 toml==0.10.2 tzdata==2022.5 urllib3==1.25.9 virtualenv==20.2.1 Werkzeug==0.15.4 whitenoise==5.1.0 wrapt==1.12.1 [1]: https://i.stack.imgur.com/wUmdy.png -
How to handle IntegrityError unique constraint correctly in Django 3.2
Hello i stacked with that simple thing. I need validation with two fields in model their combination must be unique. These is work almost as want, but after i try to add a new combination it raise IntegrityError instead validation error in my form. Any workaround to handle it? #Model(is not all field but it not Necessary in my question): class AggSubnet(models.Model): region = models.ForeignKey("db_info.Region", on_delete=models.PROTECT, related_name='get_agg_by_region') subnet_ip = models.GenericIPAddressField() class Meta: constraints = [ models.UniqueConstraint(fields=['subnet_ip','region'], condition=~Q(subnet_ip__startswith='172.'), name='agg_subnet_unique'), ] def __str__(self): return f'{self.region} {self.subnet_ip}/{self.subnet_prefix}' def get_absolute_url(self): return reverse(f'{self.__class__.__name__}{DETAIL_SUFFIX}', kwargs={"pk": self.pk}) #View: class AggregateSubnetCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = AggregateSubnet template_name = 'Subnet_create.html' fields = ('region', 'subnet_ip') success_message = "%(subnet_ip)s was created successfully" def form_valid(self, form): form.instance.created_by = self.request.user form.instance.updated_by = self.request.user return super().form_valid(form) #Template I mean how i can replace: enter image description here to something like this: enter image description here -
Django Send_mail not working in production
I have the current set up and emails are pushed locally fine but it doens't in production. It is a django, docker, dokku and nginx setup hosted on a VPS. Locally I run it in docker with docker compose up and in production also with the same dockerfile. This is all the info that i thought was useful does anyone know what i have to do? settings.py ... EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("Email_Username", "") EMAIL_HOST_PASSWORD = os.environ.get("Email_Password", "") EMAIL_HOST = os.environ.get("Email_Host", "mail.domain.nl") EMAIL_PORT = os.environ.get("Email_Port", 587) ... actions.py def sendRegisterMail(modeladmin, request, queryset): for lid in queryset: print("email sending") achievements = '...' subject = "..." message = f""" ... """ send_mail( subject, message, settings.EMAIL_HOST_USER, [lid.email], fail_silently=True, ) print("email sent") dokku nginx:show-config app server { listen [::]:80; listen 80; server_name app.dispuutstropdas.nl; access_log /var/log/nginx/app-access.log; error_log /var/log/nginx/app-error.log; include /home/dokku/app/nginx.conf.d/*.conf; location / { return 301 https://$host:443$request_uri; } } server { listen [::]:443 ssl http2; listen 443 ssl http2; server_name app.dispuutstropdas.nl; access_log /var/log/nginx/app-access.log; error_log /var/log/nginx/app-error.log; ssl_certificate /home/dokku/app/tls/server.crt; ssl_certificate_key /home/dokku/app/tls/server.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; keepalive_timeout 70; location / { gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml; … -
Having venv made with powershell 5, can I safely move/upgrade my shell to powershell 7?
I have a Django project with venv made with PowerShell 5. I wonder if is it safe to install and use this project with PowerShell 7. If I would invoke my venv with a later version of PowerShell (v7), will it cause some sort of a conflict, create bugs, or clashes? Are there any data fetched by venv (and stored) related to PowerShell? -
Connect views.py to a Javascript file
I'm working on a Django project showing PDF files from a dummy database. I have the function below in views.py to show the PDF files. def pdf_view(request): try: with open ('static/someData/PDF', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type="application/pdf") response['Content-Disposition'] = 'filename=test1.pdf' return response pdf.closed except ValueError: HttpResponse("PDF not found") This function needs get connected to another function located in a javascript file. How do we connect views.py to another Javascript file? -
Django Create separate copy of a model every time a user signs up
So, I am really new to Django. I was working around an app as a part of an assignment which requires me to build a webapp with login functionality, Further the admin, shall create few tasks that will be common to all the users. So here is the model that would contain all the tasks and will be controlled by the admin: from django.db import models # Create your models here. class applib(models.Model): status_code=[ ('C','Completed'), ('P','Pending'), ] title = models.CharField(max_length=50) status=models.CharField(max_length=2,choices=status_code) point = models.IntegerField() category= models.CharField(max_length=50) subcat = models.CharField(max_length=50) applink = models.CharField(max_length=100) def __str__(self): return self.title Now I have worked around the login functionality, and I want that upon each login a copy of this model is attached to the user so that the user can has his own set of tasks. He should be able to keep track of these tasks and do the tasks independently. How do I do this without creating separate task models for each user. I know there would be a really simple explanation and solution but all I know write now is I want to inherit the tasks from the main model for each user upon user creation. Thank you. -
How does database connection pooling work with Celery (& Django) for prefork & gevent connection types?
I have a django server, alongside a celery background worker, both of them interact with a Postgres database. I have a single celery worker running gevent with 500 concurrency flag. This gives 500 threads under a single worker to run and execute tasks. My question is do all of these threads try to use the same database connection? Or will it try to create 500 connections. In a prefork pool, does it create a connection per process? I saw in django documentation (https://docs.djangoproject.com/en/4.1/ref/databases/#connection-management), it says that it allows persistent connections, so connections are reused, but I'm not sure how this translates to celery? -
Django Dataframe not able to convert timestamp to date
Django Data frame not able to convert timestamp to date in template view Query result of Select * from paper_trade where date = now()::date order by open_time is Date day open_time 2022-10-19 Wednesday 10:54 My code is as below sql_query_n = pd.read_sql_query("""Select * from paper_trade where date = now()::date order by open_time""",con=engine) df_n = pd.DataFrame(sql_query_n) json_records_n = df_n.reset_index().to_json(orient ='records') data_n = [] data_n = json.loads(json_records_n) In the django template trying to itrate and use as {{ i.date }} Date_______________day_________ open_time 1666137600000 Wednesday 1666176843000 1666137600000 Wednesday 1666185662000 1666137600000 Wednesday 1666188004000 Tried {{ i.date|date:'Y-m-d' }} but it gives empty value. What is the issue -
ImportError: cannot import name 'views' from 'birds_eye'
I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give me an error saying: ImportError: cannot import name 'views' from 'birds_eye' The following is my current directory tree of my django project: birds_eye |- accounts (app folder) |- birds_eye (actual project folder) |- clubs (app folder) |- events (app folder) |- posts (app folder) |- static |- templates And this is the actual code of what is happening: birds_eye |- birds_eye (actual project folder) |- urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path("admin/", admin.site.urls), path("test/", views.TestPage.as_view(), name="test"), path("thanks", views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path("accounts/", include("django.contrib.auth.urls")), # Events --> Calendar, Posts --> Feed | Expected to finish later on. Uncomment when done. # path("posts/", include("posts.urls", namespace="posts")), # path("events/", include("events.urls", namespace="events")), path("clubs/", include("clubs.urls", namespace="clubs")), path('surveys', include('djf_surveys.urls')), ] Is there any solution to this? (I can edit the question in order to provide more resources from my project) -
Django media returns the 404 NOT FOUND when I try to GET media using Axios
I'm trying to get media from django but I get this 404 NOT FOUND error message in the console xhr.js?1a5c:244 GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) My product/urls.py code is this from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>/', views.ProductDetail.as_view()), ] the first path works perfectly but the second one shows this error GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) -
Django rest framework browsable api show null for manytomany field
I am going to implement api for blog app using DRF ModelViewSet: This is how i implemented: views.py from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.response import Response from .serializers import PostSerializer, CategorySerializer from ...models import Post, Category from rest_framework import viewsets from rest_framework.decorators import action from .permissions import IsOwnerOrReadOnly from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from .paginations import DefaultPagination class PostModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] serializer_class = PostSerializer queryset = Post.objects.filter(ok_to_publish=True) filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = { "category": ["exact", "in"], "author": ["exact"], "ok_to_publish": ["exact"], } search_fields = ["title", "content"] ordering_fields = ["publish_date"] pagination_class = DefaultPagination @action(detail=False, methods=["get"]) def get_ok(self, request): return Response({"detail": "ok"}) class CategoryModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = CategorySerializer queryset = Category.objects.all() serializers.py from rest_framework import serializers from ...models import Post, Category from accounts.models import Profile class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name"] class PostSerializer(serializers.ModelSerializer): summary = serializers.CharField(source="get_summary", read_only=True) relative_url = serializers.CharField(source="get_relative_api_url", read_only=True) absolute_url = serializers.SerializerMethodField(method_name="get_absolute_api_url") category = serializers.SlugRelatedField( queryset=Category.objects.all(), slug_field="name", many=True ) class Meta: model = Post fields = [ "id", "title", "author", "image", "content", "summary", "category", "relative_url", "absolute_url", "ok_to_publish", "login_required", "n_views", "created_at", "publish_date", ] read_only_fields = ["author"] def get_absolute_api_url(self, obj): # It is not a standard and correct …