Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
urllib [Errno 11001] getaddrinfo failed with windows proxy
I'm running Django 3.2 with django-tenants on a Windows local dev environment. In my windows hosts file I have: 127.0.0.1 *.localhost ...so that I am able to use subdomains with django-tenants. E.g. http://mysub.localhost:8000. When running ./manage.py runserver the dev server runs perfectly. However, when trying to execute urlopen in my code I get an error: >>> html = urlopen('http://mysub.localhost:8000') Traceback (most recent call last): [...] urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed> As far as I can tell the error is due to the proxy settings on my windows machine (this does not fail in production), but I am unsure how to resolve it? -
How to server Django media files on apache2 and docker
I'm Running a django app on apache2 using docker, everything works great but when i try to open an uploaded file ( media file) it says an URL not found error like : physical/path/to/file/filename.jpg doesnt exsits so it converts the url to a phyical path from inside the docntainer.. Here are my files: DockerFile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 5432 WORKDIR /var/www/html/demo_app #CMD ["apache2ctl", "-D", "FOREGROUND"] #CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose.yaml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./data/static:/var/www/html/demo_app/static - ./data/upload:/var/www/html/demo_app/upload ports: - '5432:5432' environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html # command: sh -c 'python manage.py migrate && … -
how i login to my new user account using login(request )
in my base.html i wrote this code {% if user.is_authenticated %} <div class="btn-group" > <button class="btn btn-primary" type="button" data-bs-toggle="dropdown" data-bs-auto-close="true" aria-expanded="false"> welcome {{user.username}} </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">profile</a></li> <li><a class="dropdown-item" href="#">change password</a></li> <li><a class="dropdown-item" href="{% url 'logout'%} ">logout</a></li> </ul> </div> {%else%} <a href="#" class ="btn btn-outline-secondary">login</a> <a href="{%url 'signup'%}" class ="btn btn-outline-primary">signup</a> {%endif%} but everytime i create a new user it always shwos the ELSE condition html this is my views: ''' from django.shortcuts import render, redirect from django.contrib.auth import login as auth_login from .forms import SignUpForm def signup(request): form = SignUpForm() if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): user =form.save() auth_login(request, user) return redirect('index') return render(request, 'signup.html', {'form': form}) ''' what is the problem -
Django : HttpRequest.__init__() takes 1 positional argument but 2 were given
So I simply want when I click on the particular article to output its slug, for example if the slug of the given article is django-rules then i want it to be outputted as django-rules when i click on it. just that here is my model from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add = True) #add in tubnail and author later def __str__(self): return self.title def snippet(self): return self.body[:50]+'...' Here is my views.py from datetime import date from django.shortcuts import render from .models import Article from django.http import HttpRequest # Create your views here. def article_list(request): articles = Article.objects.all().order_by('date') return render(request,'articles/article_list.html', {'articles': articles} ) def article_detail(request, slug): return HttpRequest(slug) url.py from posixpath import relpath from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from . import views app_name = 'articles' urlpatterns = [ path('', views.article_list, name = 'list'), path('<slug:slug>/', views.article_detail, name = 'detail'), ] Please dont suggest to add as_view() its not working. -
Azure FTPS How to find the deployed project files
I am using Azure FTP to update the project files after they are deployed via CLI I get to /site/wwwroot I see a tar file, where do I find all the project files. Requirement is to update single file each time to test it. -
elasticsearch.exceptions.RequestError: RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]',
I'm writing a site on Django, I'm currently implementing a search system using django-haystack via elasticsearch I did everything as in the official documentation, but when I execute the command python manage.py rebuild_index I am getting an error elasticsearch.exceptions.RequestError: RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') Here is the full error trace: GET http://127.0.0.1:9200/haystack_books/_mapping [status:401 request:0.004s] PUT http://127.0.0.1:9200/haystack_books [status:401 request:0.003s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.004s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.006s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.008s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.006s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.013s] [ERROR/MainProcess] Failed indexing 1 - 11 (retry 5/5): RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POS T]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') (pid 3932): RequestError(400, 'no handler found for uri [/haysta ck_books/modelresult/_bulk] and method [POST]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') Traceback (most recent call last): File "D:\Джанго проект\venv\lib\site-packages\haystack\management\commands\update_index.py", line 111, in do_update backend.update(index, current_qs, commit=commit) File "D:\Джанго проект\venv\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 222, in update bulk(self.conn, prepped_docs, index=self.index_name, doc_type="modelresult") File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 410, in bulk for ok, item in streaming_bulk( File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 329, in streaming_bulk for data, (ok, info) in zip( File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 256, in _process_bulk_chunk … -
Saving objects to postgresql with DJango in UTC instead of local timezone?
I have a column in my table called "signed_up_date", which I am using the auto_now_add=True parameter with the DateTimeField() function. I want this function to save timestamps to the PostgreSQL DB in UTC instead of my local time (EST) which it is currently doing. Barebones version of the model for quick ref below: class TutorTest(models.Model): signed_up_on = models.DateTimeField(auto_now_add=True) Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True I thought based on the docs, if I have Time_Zone set to UTC and UTC_TZ set to True, then the default behavior of Django would be to save as UTC. I know when I check postgresql timezone I get: SHOW TIMEZONE; TimeZone ------------ US/Eastern (1 row) I just tried a new model with timezone.now() and it looks like in the db shell I get: datetime.datetime(2022, 9, 21, 14, 36, 16, 670726, tzinfo=datetime.timezone.utc) But the db saved it as: 2022-09-21 10:35:26.633116-04 I guess it's the DB in this situation? Confused lol -
Django cart management
I work on a cart management application, I use the django-shopping-cart 0.1 package, At the level of my project I use a dictionnary the products then add them to the basket, Also noted the products are added by setting the product code. def cart_add(request, code): dico={"produits":[{'code':'fg21','name':'coca cola','prix':1500}, {'code':'br21','name':'pomme','prix':1800}]} all_produits=dico['produits'] all_product = next((item for item in all_produits if item["code"] == code), None) if selected_product != None: cart = Cart(request) product = selected_product cart.add(product=product) return render(request, 'cart/detail.html',context) Here the error comes from the cart.py module of django-shopping-cart 0.1 At line level (id = product.id) I am told the dic object has no code attribute even if I do (id=product.code) cart.py class Cart(object): def __init__(self, request): self.request = request self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, action=None): """ Add a product to the cart or update its quantity. """ id = product.id newItem = True if str(product.id) not in self.cart.keys(): self.cart[product.id] = { 'userid': self.request.user.id, 'product_id': id, 'name': product.name, 'quantity': 1, 'price': str(product.price), 'image': product.image.url } else: newItem = True for key, value in self.cart.items(): if key == str(product.id): value['quantity'] = … -
How to change the name of document in filefield url to an ID of document in Django/DRF
I want to change my url of document so that in response instead of returning with the name of the document, it should return the id of the document. so, /nononoo.txt becomes like this /2 ( id of the document) This is my response that i am getting, "id": 2, "document": "http://127.0.0.1:8000/images/nononno.txt", "filesize": "13 bytes", "filename": "nononno.txt", "mimetype": "text/plain", "created_at": "2022-09-21" I want to change this /nononoo.txt to the id of the document so that it becomes like this "document": "http://127.0.0.1:8000/images/2(id of the current document uploaded)" models.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField(max_length=350 ,validators=[FileExtensionValidator(extensions)]) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) def save(self, force_insert=False, force_update=False, *args, **kwargs): self.filename=self.document.name self.mimetype=mimetypes.guess_type(self.document.url)[0] self.filesize=self.document.size super().save(force_insert, force_update, *args, **kwargs) class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def sizeoffile(self): x = self.document.size y = 512000 if x < y and x < 1000 : value=round(x, 0) ext = ' bytes' elif x < y and x >= 1000 and x < 1000*1000: value = round(x / 1000) ext = ' KB' elif x < y * 1000 and x >= 1000*1000 and x < 1000*1000*1000 : value = round(x / (1000 * 1000), 2) ext = ' MB' elif x >= 1000*1000*1000: value = round(x … -
How to re-save a ModelForm?
I instantiate a ModelForm based on some input data, and then I generate/fetch some new data based on that input data, and want to refresh my ModelForm with the new data and then save it. I would rather like to use ModelForms as much as possible and avoid having to use the associated Model object directly when it comes to saving/validation and other stuff (e.g. white-space trimming). One solution would be to instantiate another new ModelForm based on the new (and the previous) data and feeding it the generated Model object via instance argument, then save() again, but, is there another better/neater/more optimized way, without having to instantiate two ModelForms? [app].models.py: from django.db import models from .custom_fields import HTTPURLField from .function_validators import validate_md5 class Snapshot(models.Model): url = HTTPURLField(max_length=1999) content_hash = models.CharField(max_length=32, default='00000000000000000000000000000000', validators=[validate_md5]) timestamp = models.DateTimeField(auto_now=True) [app].forms.py: from django import forms from .models import Snapshot class SnapshotModelForm(forms.ModelForm): class Meta: model = Snapshot fields = ('url', 'content_hash') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content_hash'].required = False [app].views.py: from django.http import HttpResponse from .forms import SnapshotModelForm def index(request): snapshot_form = SnapshotModelForm( data={'url': ' http://www.baidu.com/ '}) try: model_instance = snapshot_form.save(commit=False) generated_new_content_hash = ' 21111111121111111111111111111111 ' snapshot_form2 = SnapshotModelForm(instance=model_instance, data={'url': model_instance.url, 'content_hash': generated_new_content_hash }) … -
'corsheaders' could not be found but it is installed
I am trying to add the cors header as instructed by https://pypi.org/project/django-cors-headers/ However, when I try to run the server i get 'Module not found: corsheaders', even though it is installed. Any idea what could be wrong? settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True -
Graphene_django can not use <class 'taggit.managers.TaggableManager'> field
the best way to used tagged.managers.TaggableManager with Graphql graphene_django? where I try to use a model with taggableManager Field, Graphql displays the following error: Don't know how to convert the Django field app.Asset.keywords (<class 'taggit.managers.TaggableManager'>) -
Cannot upload image to server
I am trying to upload image to the server. I received Imagename (string) and Imagefile (multipart) from android, Imagename is successfully saved with below algorithm but Imagefile wasn't. I think the problem is the column name of image figure is not imgfigure but "Character". However, @Part("imgfigure") imgfigure : MultipartBody.Part gives me an error. What should I do? Here is the code below, @view.py @api_view(['POST']) def Createtest(request): if request.method == "POST": serializer = FullSerializer(request.POST, request.FILES) if serializer.is_valid(): serializer.save() return JsonResponse({'code':'0000', 'msg': 'saved'}, status=200) return JsonResponse({'code':'1001', 'msg': 'failed'}, status=200) @serializer.py class FullSerializer(forms.ModelForm): class Meta: model = Character fields = ('imgname','imgfigure') @model.py class Character(models.Model): imgname = models.TextField(max_length=20) imgfigure = models.ImageField(upload_to='Image/',blank=True, null=True) Here is the request data in Django //The result of request.POST = <QueryDict: {'imgname': ['"session1"']}> //The result of request.FILES = <MultiValueDict: {'character': [<InMemoryUploadedFile: haruRoll.jpg (image/*)>]}> Here is Retrofit service from Kotlin interface SessionCreateService { @Multipart @POST ("/character/create/") fun SessCreate( @Part("imgname") imgname:String, @Part imgfigure : MultipartBody.Part, ):Call<SessionCreate_o> //output } -
How to get many to many value in Django template
I have 2 app: authors_app and books_app Authors_app Models.py class Author(models.Model): name = models.CharField(max_length=250, unique=True) Books_app Models.py class Book(models.Model): author = models.ManyToManyField(Author, related_name='authors') Authors_app Views.py class AuthorBio(DetailView): model = Author template_name = 'author-bio.html' Problem I need to get all the book published by the author. In my template I try: {% for book in author.books.all %} ... {% endfor %} But this doesn't work Question How can I get all the books by the author -
How to update/change attribute in Django Class Based View Test
I created a mixin that requires an attribute to be added to a Class Based View (cbv) and it works as expected - but I'm having a tough time 'testing' that mixin specifically. Here is my test: class TestView(GroupRequiredMixin, View): group_required = ("test_group",) raise_exception = True def get(self, request): return HttpResponse("OK") class GroupRequiredMixinTest(TestCase): def setUp(self): group = GroupFactory(name="test_group") self.user = UserFactory(groups=(group,)) def test_view_without_group_required_improperly_configured(self): rfactory = RequestFactory() request = rfactory.get("/fake-path") request.user = self.user view = TestView() view.group_required = None with self.assertRaises(ImproperlyConfigured): view.as_view()(request) This test errors with this message: AttributeError: This method is available only on the class, not on instances. What is the 'appropriate' way to test this? Should I be setting up a unique class for each situation I want to test? Or is there a way I can dynamically change that attribute on an instance like in my test that fails? -
Create method for foreign key in nested serializer
I have an error when I try to create a new data. I was looking for information about my error and all of them recommended me to implement a create method in the serializers. I implemented that method but at the time of creating the data, it isnt creating the data that are called through the foreign key. apps.sip_telefono.models class marca_telefono(models.Model): id_marca_telefono = models.AutoField(primary_key=True) no_marca_telefono = models.CharField(max_length=100, blank=True, null=True,) class modelo_telefono(models.Model): id_modelo_telefono = models.AutoField(primary_key=True) no_modelo_telefono = models.CharField(max_length=100, blank=True, null=True,) id_marca_telefono = models.ForeignKey(marca_telefono, on_delete=models.CASCADE) class sip_telefono(models.Model): id_sip_telefono = models.AutoField(primary_key=True) id_marca_telefono = models.ForeignKey(marca_telefono, on_delete=models.CASCADE, blank=True, null=True,) id_modelo_telefono = models.ForeignKey(modelo_telefono, on_delete=models.CASCADE, blank=True, null=True,) no_mac = models.CharField(max_length=100, blank=True, null=True,) appps.anexos_sip.model class sip_buddies(models.Model): id_sip = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) type = models.CharField(max_length=6, default='friend') telefono = models.ForeignKey(sip_telefono, on_delete=models.CASCADE, blank=True, null=True,related_name="telefono") apps.anexos_sip.serializer class SipTelefonoSerializer(serializers.ModelSerializer): id_marca_telefono = serializers.CharField(source ='id_marca_telefono.no_marca_telefono') id_modelo_telefono = serializers.CharField(source ='id_modelo_telefono.no_modelo_telefono') class Meta: model = sip_telefono fields = ('id_marca_telefono','id_modelo_telefono','no_mac') class AnexoListarSerializer(serializers.ModelSerializer): telefono = SipTelefonoSerializer(required=False) class Meta: model = sip_buddies fields = ('name', 'type', 'telefono') def create(self,validated_data): telefono_data = validated_data.pop('telefono', None) sip = sip_buddies.objects.create(**validated_data) sip.save() for tel in telefono_data: sip_telefono.objects.create(sip=sip, **tel) return sip def update(self,instance,validated_data): instance.name = validated_data.get('name',instance.name) instance.type= validated_data.get('type',instance.type) instance.save() telefono_data = validated_data.pop('telefono') tel = instance.telefono tel.id_marca_telefono = telefono_data.get('id_marca_telefono',tel.id_marca_telefono) tel.id_modelo_telefono = telefono_data.get('id_modelo_telefono',tel.id_modelo_telefono) tel.no_mac = telefono_data.get('no_mac',tel.no_mac) … -
Django multi tenant with SSO dynamically change settings variable CLIENT_ID,CLIENT_SECRET,TENANT_ID
How can i change these hardcoded ID's CLIENT_ID,CLIENT_SECRET,TENANT_ID in settings.py depending upon the tenants logged in users I had implemented django SSO using django_auth_adfs. How can i change these ID's value dynamically based on individual users of each tenant logged in -
django Forbidden error with httpd and wsgi
I am using RH8, httpd, wsgi and django. When I attempt to browse to the web page, I get the following error in the web server log: [Wed Sep 21 13:35:09.382780 2022] [core:error] [pid 433487:tid 139782344644352] (13)Permission denied: [client x.x.x.x:28351] AH00035: access to /favicon.ico denied (filesystem path '/opt/django/dcn_automation/dcn_automation') because search permissions are missing on a component of the path, referer: http://xxxx/ This is configured using /etc/httpd/conf.d/django.conf. The contents of which are below. I have tried "Require all granted" inside the files wsgi.py part. This gives the same result. LoadModule wsgi_module "/opt/django/djangoenv/lib64/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so" #WSGIPythonHome "/opt/django/djangoenv" <VirtualHost *:80> <Directory /opt/django/dcn_automation/dcn_automation> <files wsgi.py> Order allow,deny Allow from all </files> </Directory> WSGIDaemonProcess dcn_automation WSGIProcessGroup dcn_automation WSGIScriptAlias / /opt/django/dcn_automation/dcn_automation/wsgi.py process-group=dcn_automation </VirtualHost> -
How to render an image in Django?
I am using the latest version of Django and I am having problems rendering my images. My img tag doesn't work so I googled it and the problem seems to be the static files. So I followed some tutorials online but none of them worked for me. It will be awesome if you could provide me with some guidance, thanks. My index.html is in landing/templates/landing and my static folder is in the root Do I need to move my static folder else where, do I need to add some line of code? -
Display values from a dictionary in python
I converted the python dictionary into a python object, but I can't display the values of the sub-array D Views.py def dictToObject(request): dictionnaire={'A': 1, 'B': {'C': 2},'D': ['E', {'F': 3}],'G':4} obj=json.loads(json.dumps(dictionnaire)) context={'obj':obj} return render(request,'cart/cart_detail.html',context) cart_detail.html {{ obj.D[0] }} {{ obj.D[1].F }} I get an error, I don't know why? -
How to update changes to Azure app service after it's deployed from CLI
IDE used is VSCode. Deployment is done using CLI The command I am using doesn't update it as I have checked the code files using ssh under development tools in azure portal az webapp update --name <name> --resource-group <resource group name> -
How to send nested dictionary as params in python requests.get?
import requests qp_args = {"query_params": {"list1": [], "list2": [], "list3": [], "data": "something"}} data = requests.get(url="Service URL", params = qp_args, timeout=2) # This doesn't work for me, since the client is receiving query_params in chunks, like, # url/?query_params=list1&query_params=list2&query_params=list3&query_params=data what is the correct way to send nested dictionary in the query_params in request.get? -
Django query fetch foreignkey association without N+1 queries in database
I have two models, Product and Price. I have used the ForeignKey association of the Django models to define the association between product and price. the scenario is, one product can have multiple prices according to size. On the home page, I have to fetch all the products with their prices and need to show their price(probably base price). Following is the code that I tried. class Product(BaseModel): name = models.CharField(max_length=50) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL, help_text='Please add new category if not given.') image = models.ImageField(upload_to='images/') tag = models.ManyToManyField(Tag, help_text='You can add multiple tags') slug = models.SlugField(unique=True, null=True) time = models.TimeField(verbose_name='Time Required') class Price(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.FloatField(validators=[MinValueValidator(0)]) amount = models.FloatField(validators=[MinValueValidator(0)]) Then in the view.py file class ProductListView(ListView): model = Product context_object_name = 'products' paginate_by = 32 def get_context_data(self,*args, **kwargs): object = super(ProductListView, self).get_context_data(*args, **kwargs) object['categories'] = Category.objects.order_by('name') return object def get_queryset(self): return Product.objects.order_by('name') In the template, I am able to get and loop through the categories and products but I am not able to access the related prices of each product. If I tried something in the get_context_data, will it cause N+1 queries to fetch prices for every product? In the template I tried to use … -
DJANGO - View/update; No TwitterModel matches the given query
I am having trouble updating/viewing my table with models and forms. I should be able to check my table objects when i go to /twitter/edit/PK but I'm getting error message that is telling me 'No TwitterModel matches the given query.' This is my models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class TwitterModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Twitter_API_key = models.CharField(max_length=110, default='default') Twitter_API_key_secret = models.CharField(max_length=110, default='default') Twitter_API_token = models.CharField(max_length=110, default='default') Twitter_API_token_secret = models.CharField(max_length=110, default='default') def __str__(self): return self.user.username This is my forms.py from django import forms from .models import TwitterModel class TwitterUpdateForm(forms.ModelForm): class Meta: model = TwitterModel fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"] Those are my views.py from dataclasses import fields from gc import get_objects from re import L from django.shortcuts import render, redirect from .models import TwitterModel from .forms import TwitterUpdateForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView) from django.shortcuts import get_object_or_404 # Create your views here. @login_required def twitter(request): if request.method == 'POST': tw = TwitterUpdateForm(request.POST) if tw.is_valid: obj = tw.save(commit=False) obj.user = request.user obj.save() messages.success(request, f'NICE!') return redirect ('twitter') else: tw = TwitterUpdateForm() context = {'tw': tw} return render(request, 'twitter_container/twitter_container.html', context) def twitter_edit(request, pk=None): … -
How to turn off reverse relation within same model in django
I have the following django model class Course(models.Model): name = models.CharField(max_length=50) pre_req_courses = models.ManyToManyField('self', default=None) def __str__(self): return self.name when I create courses in following way: course1 = Course.objects.create(name='Course1') course1.save() course2 = Course.objects.create(name='Course2') course2.save() course2.pre_req_courses.set(course1) when I run the following command I get: course2.pre_req_courses.all() >>> <QuerySet [<Course: Course1>]> course1.pre_req_courses.all() >>> <QuerySet [<Course: Course2>]> Wht I want is: course2.pre_req_courses.all() >>> <QuerySet [<Course: Course1>]> course1.pre_req_courses.all() >>> <QuerySet []> How can I achieve this