Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django js tabs keep selected tab on page refresh
I'm working with js tabs (https://www.w3schools.com/howto/howto_js_tabs.asp) in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. Is there an easy way to do it? I found similar questions but they are not valid for my case... This is the script I'm using: function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " active"; } -
How to fix css in django cycle?
I want to do div titleblog and do magrin-top:100px,but it isnt working in django cycle..Idk why.I tried to do <a class='titleblog',but it wasnt working). P.S css file is attached at html file.CSS file is working,because navigation panel is displaying. blog.html <div class="titleblog"> {% for i in objects %} <a href="{{i.id}}">{{i.titleblog}}</a> <b>{{i.message | lower}}</b> {% endfor %} </div> home.css .titleblog{ margin-top: 100px; } -
Exposing simple types on WSDL with Spyne
We are trying to build a SOAP app with Django + Spyne building specific required endpoints. The exposed WSDL has to precisely match a predetermined XML file, including the custom simpleType definitions. We're currently failing to show the simple type definitions on our WSDL, everything else matches up precisely. A simple example is the following hello world app: import logging logging.basicConfig(level=logging.DEBUG) from spyne import Application, rpc, ServiceBase, \ Integer, Unicode, SimpleModel from spyne import Iterable from spyne.protocol.xml import XmlDocument from spyne.protocol.soap import Soap11 from spyne.interface.wsdl import Wsdl11 from spyne.server.django import DjangoApplication from django.views.decorators.csrf import csrf_exempt class IdType(SimpleModel): __type_name__ = "IdType" __namespace__ = 'spyne.examples.hello' __extends__ = Unicode class Attributes(Unicode.Attributes): out_type = 'TxnIdType' class HelloWorldService(ServiceBase): @rpc(IdType, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, TxnIdType, times): for i in range(times): yield 'Hello, %s' % TxnIdType application = Application([HelloWorldService], tns='spyne.examples.hello', interface = Wsdl11(), in_protocol=Soap11(validator = 'lxml'), # out_protocol=XmlDocument(validator='schema') out_protocol=Soap11() ) hello_app = csrf_exempt(DjangoApplication(application)) Which yields the following WSDL: <wsdl:definitions xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:plink="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:wsdlsoap11="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap12enc="http://www.w3.org/2003/05/soap-encoding" xmlns:wsa="http://schemas.xmlsoap.org/ws/2003/03/addressing" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="spyne.examples.hello/types" xmlns:s0="spyne.examples.hello" targetNamespace="spyne.examples.hello/types" name="Application"> <wsdl:types> <xs:schema targetNamespace="spyne.examples.hello/types" elementFormDefault="qualified"> <xs:import namespace="spyne.examples.hello" /> <xs:complexType name="say_helloResponse"> <xs:sequence> <xs:element name="say_helloResult" type="xs:string" minOccurs="0" nillable="true" /> </xs:sequence> </xs:complexType> <xs:complexType name="say_hello"> <xs:sequence> <xs:element name="IdType" type="s0:IdType" minOccurs="0" nillable="true" /> <xs:element name="times" type="xs:integer" minOccurs="0" … -
Django - Pathing Issue (I think!)
I've created a restuarant booking system using Django. Trying to achieve full Crud functionality. Just trying to sort out the update and delete. So basically when i open the user account it comes up with the reservations they've made and the option to edit or Delete them. Where my issue is is when i have my url paths as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"), path('view/<slug:pk>/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete/<slug:pk>/', DeleteReservationView.as_view(), name="delete_reservation"), ] It won't load the account screen as it says: error screen 1 and when I change my paths to as follows: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit_reservation', EditReservationView.as_view(), name="edit_reservation"), path('view_reservation/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete_reservation/', DeleteReservationView.as_view(), name="delete_reservation"), ] It does load the account screen but when i hit the Edit or Delete button i get the following: error screen 2 Relatively new to Django so any help is grealy appreciated. Thanks in adance -
RuntimeError: Model class mainpage_authentication.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Before applying models to my project everything was okay. But when I just applied them, the system crushed. I'm a freshmen learning Django, so will be grateful for an explanation, and a solution, if possible. My code: admin.py from django.contrib import admin from .models import User admin.site.register(User) apps.py from django.apps import AppConfig class AuthenticationPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mainpage_authentication' forms.py from django import forms from .models import User class AuthenticationLoginForm(forms.Form): class Meta: model = User fields = ['username', 'password'] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage_authentication', ] views.py from django.shortcuts import render from django import views from mainpage_authentication.forms import AuthenticationLoginForm class MainPageView(views.View): def get(self, request): return render(request, 'mainpage.html') class AuthenticationLoginPageView(views.View): def get(self, request): form: AuthenticationLoginForm = AuthenticationLoginForm() return render(request, 'authentication-page.html', {"form": form}) -
how to upload all type of file to cloudinary using django with filefield
hello guys i want to upload all type of file to cloudinary this is my model i don't want to upload a specific kind of file but all type pleaze help me class post(models.Model): titre=models.CharField(unique=True,null=True,max_length=100) description=models.TextField(null=True,blank=True,max_length=400) T=models.CharField(default="image",blank=True,max_length=50) image=models.FileField(null=True) cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) datepost=models.DateTimeField(auto_now_add=True,blank=True) user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True) vue=models.IntegerField(default=0,blank=True) def __str__(self): return self.titre def save(self, *args ,**kwargs): #cette partie permet de generer un identifiant unique f=self.image.read(1000) self.image.seek(0) mime=magic.from_buffer(f,mime=True) if "video" in mime : self.T="short" super(post,self).save(*args,**kwargs) thanks for your helps and sorry for my bad english -
How can i join two prefetch related in Django query
i have to do a django filter with complex form query and i don't have experience with select_related and prefetch_related methods. models.py: class User(models.Model): class Park(models.Model): class Plot(models.Model): owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, null=True, related_name='plots') park = models.ForeignKey('Park', verbose_name=_('Park'), on_delete=models.SET_NULL, null=True, related_name='plots') class Building(models.Model): plot = models.ForeignKey('Plot', verbose_name=_('Plot'), on_delete=models.SET_NULL, blank=True, null=True, related_name='plot_buildings') owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, blank=True, null=True, related_name='owner_buildings') tenant = models.ForeignKey(get_user_model(), verbose_name=_('Tenant'), on_delete=models.SET_NULL, blank=True, null=True, related_name='tenant_buildings') I need to get all de user that are owner of a plot or a building or tenant of a building. i have this for now... filters.py: class UserApiFilter(filters.FilterSet): park_id = filters.CharFilter(method='filter_by_park') def filter_by_park(self, queryset, name, value): params = {name: value} result = queryset.prefetch_related(Prefetch('plots', queryset=app_models.Plot.objects.filter(**params))) Anybody could help me please? Thanks in advance. -
AttributeError at /media/.. when requesting file in media folder Django development stage
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error: AttributeError at /media/test.png This FileResponse instance has no content attribute. Use streaming_content instead. Request: http://localhost:8000/media/test.png I added below to the url patterns: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And below to the settings: STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' Static files are working just fine. What do I overlook? Thanks! -
Django How to display either an image or pdf
I have a model with file upload field where users can upload either an image or a pdf. What is the best way to display the upload in a template when it can be either an image or a pdf. I have seen a fairly complex ajax based solution. Is there a better way? -
django error: The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'
I extended my accounts custom user model using a one-to-one field and it worked fine. But when I tried customizing it to display more info such as the staff_number and location, the following error is returned: <class 'accounts.admin.staffAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.clinic_staff'. the staffAdmin class doesn't have username listed as a list_display and the clinic_staff is just returning the username. I'm stuck on what to do? this is my accounts>models.py code: from datetime import date import email import imp from pyexpat import model from tkinter import CASCADE from tkinter.tix import Tree from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None,): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
How can I migrate my existent sqlite db to postgres on heroku?
I deployed my django app on heroku and I can't see my database on the site(users, posts..). If i create a new superuser(couldn't log in with my old superuser so I had to create another one) or any other user, content disappears after some time.. Correct me if I'm wrong I thought heroku converts that for me automatically when I deploy my app, anything I missed? And I did migrate from the heroku CLI Setting: import os import django_heroku from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = secretkey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["network50web.herokuapp.com"] # Application definition INSTALLED_APPS = [ 'crispy_forms', 'network', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'import_export' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'project4.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': (BASE_DIR, 'network/templates'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project4.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases … -
Passing multiple parameters to django url template
I am trying to pass multiple url parameters from a django templated to be used by a view function. Below are my codes : A snippet from the template from where the parameters will be passed onto : <a href="{% url 'coordinator_assign_project_recommendations' group_id=row.group client_id=row.client project_id=row.project_id %}" class="btn btn-primary">Assign</a> The view function : def assign_recommended_project(request, group_id, client_id, project_id): group = StudentGroup.objects.get(id=group_id) group.client = client_id group.project = project_id group.save() project = Project.objects.get(id=project_id) project.is_assigned = True project.save() return redirect("coordinator_view_groups") The url of the view function : path( "coordinator/assign_recommended_project/<str:group_id/str:client_id/str:project_id", assign_recommended_project, name="coordinator_assign_project_recommendations", ), This is the error that is shown : Can someone please help me solve this. Thanks. -
NoReverseMatch at when calling url
I can't work out why im getting this error NoReverseMatch at / when calling <a href="{% url 'show_token_details' token.id %}"> def show_token_details(request,token_id): token = Token.objects.get(token_id == token_id) return render(request, 'ecommerceproductdetails.html', {}) path("token/<int:token_id>", views.show_token_details, name='show_token_details'), What am I missing here? Thanks -
How can I pass in the login/register data for my django-rest api in the form of a url?
I am following along with a book on the django-rest framework and I am having issues grasping a certain concept. The book uses the built-in Browsable API feature to do basic CRUD and LOGIN/LOGOUT/REGISTRATION functionality. What it fails to mention is how I can achieve such functionality using only the URL, which would be needed for, say connecting the API to the frontend of a REACT app. Example: I have an API which displays Posts and this path shows all posts: path('api/v1/', include('posts.urls')), I want to use this path for example, to register. path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), How would the URL look like ? -
Why are my images not showing at the index page?
I am trying to create an auction website where the users can input an image url and bid on the entries. The issue I am currently having is that my images are not reflecting on my index page except I hard code it. I'm not sure what I am doing wrong as I have tried using different options such as using an imageField and trying to convert the URL to an image(This didn't work) and I have tried tweaking the codes but still having the same issue. Please assist a newbie URL.PY path("create/", views.create_listing, name="create_listing"), MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) # image_upload = models.ImageField(upload_to='images/') image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) category = models.CharField( choices=select_category, max_length=12, default=MODERN, ) created_at = models.DateTimeField(auto_now_add=True) FORMS.PY class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid', 'image_url', 'category'] VIEWS.PY def create_listing(request): form = AuctionForm() user = request.user if request.method == 'POST': form = AuctionForm(request.POST, request.FILES) images = Auction.objects.get('image_url') if form.is_valid: context = { 'user': user, 'images': images } form.save() return redirect('index', context) else: form = … -
Symmetrical link between two objects in Django
I have a model with all the info of a plant and another model which consists of creating links between these plants. But when I create a link between two plants for example I create an ideal link between basil and garlic in the Django admin, I don't have the symmetrical link between garlic and basil. Should we add symmetrical = true in the model? Here is Plant model : from django.db import models class Plant(models.Model): class LEVEL(models.TextChoices): NONE = None EASY = 'easy', MEDIUM = 'medium', HARD = 'hard' class SUNSHINE(models.TextChoices): NONE = None FULL_SUN = 'full_sun', SHADOW = 'shadow', SUNNY = 'sunny', MODERATE = 'moderate' class IRRIGATION(models.TextChoices): NONE = None WET = 'wet', WEAKLY = 'weakly', MOIST = 'keep_soil_moist', GENEROUSLY = 'generously', SLIGHTLY_DAMP = 'slightly_damp', COVERED_WITH_WATER = 'covered_with_water' class SOIL_N(models.TextChoices): NONE = None HUMUS = 'humus', LIGHT = 'light', CLAY = 'clay', DRAINED = 'drained', ALL_TYPE = 'all_types' class SOIL_T(models.TextChoices): NONE = None POOR = 'poor', MEDIUM_SOIL = 'medium_soil', RICH = 'rich', FERTILE = 'fertile', DRAINED = 'drained', ADD_PEBBLES = 'add_pebbles', ALL_TYPE = 'all_types' class HARDINESS(models.TextChoices): NONE = None VERY_FRAGILE = 'very_fragile', FRAGILE = 'fragile', RUSTIC = 'rustic', MEDIUM = 'medium', SUPPORT_FRESHNESS = 'support_freshness', # COLD_RESISTANT = 'cold_resistant' … -
HTML show image if it exists and show nothing if it doesn't
I need to display an image on my HTML page but only if it exists in my directory. If it doesn't, then show nothing. How can I write a function that checks if the image exists, then if yes, display it if no, don't show anything? I am using django as a back end. -
Django channels Disconect after closing the tab
I'm new to Django channels and I'm building a simple chatroom. With this chatroom, I want to disconnect a user if he closes the browser tab and if he reopens the tab with the same link, I want to reconnect him to the same chat that he was. How can I do that? -
Django not finding environment variables set by Github Actions
I have a Github Action that creates a Docker image, and the issue I am having is that when I docker logs backend I get an error like: File "/usr/src/app/api/settings/common.py", line 165, in <module> AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"] File "/usr/local/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID' As part of my .yml for GitHub I have this code which from research should inject the environment variables into my Docker image. jobs: build_and_deploy_backend__production: runs-on: ubuntu-latest steps: - name: Checkout the repo uses: actions/checkout@v2 - name: Build image run: docker build -t backend . env: AWS_ACCESS_KEY_ID: ${{ secrets.GLOBAL_AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.GLOBAL_AWS_SECRET_ACCESS_KEY }} I am wondering if there is anything obvious that I am doing wrong. -
How i can implement asyncio in the below on function
Basically i wanna to extract youtube video information but "ydl.extract_info(video_url_id, download=False)" take 3 seconds per request. and atleast 50 to 100 request is required and it takes alot time. def get_video_urls(video): ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'}) final_list= [] for url in video: video_url_id= f'https://www.youtube.com/watch?v={url["snippet"]["resourceId"]["videoId"]}' with youtube_dl.YoutubeDL({'forceurl':True, 'quiet':True, 'skip_download':True}) as ydl: result = ydl.extract_info(video_url_id, download=False) final_list.append(result['formats'][-2]['url']) return final_list -
How to show the progress of PG stored procedure in a DJango Application
We have a long-running stored procedure that can be invoked from a Django web application. How can I show the status on the stored procedure in my web page, say in-progress, error, or completed in my web page? -
Can't figure out DeclarativeMeta error with alembic and sqlalchemy in django project
I could use some help figuring out how to debug this: I suspect that there is something wrong with my models.py file but the error messages are pretty vague. Using Alembic and sqlalchemy instead of Django ORM (relatively new to all the above) and successfully made a migration and migrated it to alembic version folder. Whole reason I'm using alembic sql alchemy is because I am trying to hit external api and was told in another post that alembic was needed to manage migration histories or there would be issues with django tracking migrations. I have a custom command class that calls the scraper and I am passing the data to pandas dataframe then attempt to write it to database defined in my models.py file. For brevity I will just post my models.py, the end of the error log as well as link to full repo from datetime import datetime from sqlalchemy import Column, Integer, DateTime, String, Numeric, BigInteger, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from django.db import models class CMC(Base): __tablename__ = 'apis_cmc' id = Column(Integer, primary_key=True) inserted_at = Column(DateTime, default=datetime.utcnow) name = Column(String) symbol = Column(String) price = Column(Numeric) market_cap = Column(BigInteger) market_cap_dominance = Column(BigInteger) fully_diluted_market_cap … -
django connect remote postgresql
Trying to connect to a remote server, serving my posgresql My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'ubuntu@username.host.com', 'PORT': '5432', } } Getting error: django.db.utils.OperationalError: could not translate host name "ubuntu@hostname.host.com" to address: Name or service not known Where the hostname and host is of course not hostname and host, just using for this example. -
Trouble posting to many-to-many field
I am trying to post a combination object, which refers to already existing tag objects. Basically I want the tag_id field of the combination to include 2 ids referring to Tag objects. This is my code: models.py class Combination(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True) resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True) tag_id = models.ManyToManyField(Tag, null=True) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) objects = models.Manager() def __str__(self): return str(self.tag_id) or '' serializers.py class CombinationSerializer(serializers.ModelSerializer): tag_id = TagWithIdSerializer(many=True, required=False) resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(), required=True, source='resource', write_only=False) gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(), required=False, source='gameround', write_only=False) user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(), required=False, source='user', write_only=False) class Meta: model = Combination depth = 1 fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score') def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user score = 0 tag_data = validated_data.pop('tag_id') combination = Combination( user=user, gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), created=datetime.now(), score=score ) for tag_object in tag_data: combination.set(tag_id=tag_object) if len(combination.tag_id) == 2: return combination def to_representation(self, instance): rep = super().to_representation(instance) rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data return rep With this I am currently getting an AttributeError : 'Combination' object has no attribute 'set' How can I get rid of this? -
Page not found(404),Current path didn't match any of these
Views.py From django.http import HttpResponse def home(request): Return HttpResponse('Hello World') urls.py(my_app) From Django.urls import path From . Import views Urlspatterns=[ Path(' ',views.home) ] Main urls From django.urls import path, include From Django.contrib import adim Urlspatterns=[ Path('admim/',.....) Path(' ',include('my_app.urls)) Settings.py Installed apps=[ " ", " ", 'my_app', ] Why I run the server it tells me page not found, ....... current empty path didn't match any of these, my Django has been working fine until recently, even if I start a new project from scratch it ends up with same result, I'm actually at the edge of giving up on Django ,I really need help please.... thanks in advance