Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change date time format after AJAX call in Django
I have the following Datatable: $('#table').DataTable( { responsive: true, autowidth: false, destroy: true, deferRender: true, ajax: { url: '/ajax_view/', type: 'GET', data: {}, dataSrc: "" }, columns: [ {"data": "fields.filename"}, {"data": "fields.uploaded"}, {"data": "fields.updated"}, {"data": "fields.user"}, {"data": "pk"}, ], columnDefs: [ { className: 'text-center', targets: [1] }, { targets: [0], class: 'text-center', orderable: true, render: function (data, type, row) { var filename = data.replace(/^[^/]*\//,''); var buttons = '<a class="file-links" href="/media/'+data+'" target="_blank">'+filename+'</a>'; return buttons; } }, { targets: [-1], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<button type="button" value="'+data+'" class="btn btn-danger fileId"><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="white" class="bi bi-trash-fill" viewBox="0 0 16 16"><path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/></svg></button>'; return buttons; } }, ], order: [ [0, 'asc'] ], "pagingType": "numbers", dom: 'rtp' … -
Flask & MySQL connector in Python
I am using MySQL in a Python written backend without an ORM. I have a bunch of classes that provide database access services using mysqlconnector and these services may be used by the same or different API routes. They are provided as member functions using a single MySQLConnection and MySQLCursor object that is initialized in a constructor and then passed around. Is it possible to make this thread-safe without altering the design too much i.e. without requiring opening a new connection for every member function that accesses the database? -
Python Azure SDK - Incorrect datetime format inferred when reading tabular data from blobstore with from_delimited_files()
I am using the Azure Python SDK to read a tabular dataset from a Blob Store as follows: df = Dataset.Tabular.from_delimited_files(path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True) The data has four datetime columns, one of the columns reads in with no problem because there are instances where the month-day order is not ambiguous, but the other three are being inferred incorrectly as "month-day" instead of "day-month". When reading in the data I get the following warning: UserWarning: Ambiguous datetime formats inferred for columns ['Period Start', 'Period End', 'Extracted At'] are resolved as "month-day". Desired format can be specified by set_column_types. I have attempted to set the column types as below, and have tried a few different formats but all I end up with is NULL in place of all the values. df = Dataset.Tabular.from_delimited_files( path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True, set_column_types={'Period Start': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Period End': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Extracted At': DataType.to_datetime("%d-%m-%Y %H:%M:%S")}) The documentation for from_delimited_files() is here Can anyone tell me how to force from_delimited_files() to resolve the ambiguous datetimes as day-month or tell me how to use set_column_types correctly? I've worked around it temporarily by inserting a dummy row with a non-ambiguous datetime. -
Files in media directory being routed through the dynamic link gets blocked
I have a dynamic link which i declared in django urls.py as this url(r'^(?P<user_name>[a-zA-Z0-9]+)', views.dynamic_link, name="user_details"), But all the media files is not been shown in the web pages of this dynamic link although the url of those files where correct whereas all files in the static folder is been shown. I called the media file through <img src="{% get_media_prefix %}{{list.picture}}" alt="this is alt {{img}}"> This is a sample of the link of the media and static file url in the web page code /static/css/bootstrap.css /media/images/byron_cream.jpg When I tried to view images, css etc from my static folder directly from inside the browser the browser displayed the images, css etc but doing the same thing with the media files the browser was not showing up but sending page to show the url does not exist(which i created for non existing url ). On further test I saw that the url of the media file was passing through the def dynamic_link function unlike that of the static files In other to ensure that a url which exist in my database is what is being called I have written my views function to check that any url which is passed thrugh the … -
Helpdesk ticketing system for IT - opening ticket by receiving email from the customer?
I have started to learn django, and I have build a helpdesk ticketing system, right now the tickets can only be opened by admin and I want the customer to open the ticket automatically by sending email to a specific email address, I know what am asking is broad but any advise on what tools are needed to achieve this would be highly appreciated. -
values_list query is returning the foreign keys pk rather than it's value
I am trying to get all the categories currently used in Recipes without any duplicates, by querying CategoryToRecipe. class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name class CategoryToRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) query_set = CategoryToRecipe.objects.values_list('name', flat=True).distinct() query_set is returning numbers, which I assume are the ID for Category, not the name (e.g. Lunch, Dinner, etc.). How do I get the actual name string of Category? -
Unused space in sqlite
I ran sqlite3_analyzer in order to try to understand why a database consumes much more disk space than expected, even after using VACUUM. The output shows that there are many tables with extra pages used for seemingly no reason. Here is an example: *** Table ACCOUNT_EMAILCONFIRMATION and all its indices *********************** Percentage of total database...................... 2.6% Number of entries................................. 0 Bytes of storage consumed......................... 12288 Bytes of payload.................................. 0 0.0% Bytes of metadata................................. 24 0.20% Average payload per entry......................... 0.0 Average unused bytes per entry.................... 0.0 Average metadata per entry........................ 0.0 Maximum payload per entry......................... 0 Entries that use overflow......................... 0 Primary pages used................................ 3 Overflow pages used............................... 0 Total pages used.................................. 3 Unused bytes on primary pages..................... 12264 99.80% Unused bytes on overflow pages.................... 0 Unused bytes on all pages......................... 12264 99.80% Here, three pages, each 4,096 bytes are used to store zero entries. The result is that a tiny database takes hundreds of KB. This makes me suspect that the database size might quickly explode when I put my Django website into production. So, why does this happen? -
Django registration form exceeds username length. [error]
I have a custom user model that has a username field with a max_length=50. Under the custom registration form, it throws me an error when the value of the username` field is just less than 10 characters: Ensure this value has at most 50 characters (it has 170). Below are the codes that I used that is in correlation with the username field: #models.py class UserAccount(AbstractBaseUser, PermissionsMixin): username = models.CharField(null=False, blank=False, max_length=50, unique=True) #forms.py class RegisterForm(UserCreationForm): username = forms.CharField(widget=TextInput( attrs={ "class": "form-control", "id": "username", #"placeholder": "Username", })) class Meta: model = UserAccount fields = ('username',) def clean_username(self): username = self.cleaned_data.get("username") username_filter = UserAccount.objects.filter(username__iexact=username) if username_filter.exists(): self.add_error('username', "Username is already taken") return self.cleaned_data HTML <div class="row form-group"> <div class="col-sm-4 label-column"> <label class="col-form-label" for="username-input-field">Username </label> </div> <div class="col-sm-6 input-column">{{register_form.username}}</div> </div> The error only occurs when I use the registration form on the html when creating a user, but when I create the user via python manage.py shell and admin panel, it gets created without any error. -
Django why I can't access objects of another model via foreignkey?
I have two model Doctor and UserProfile. I want to access UserProfile model objects via foreignkey. here his my code: models.py class Doctor(models.Model): docter_id_num = models.CharField(blank=True,null=True,max_length=100) doctor_name = models.CharField(max_length=100) slug = models.SlugField(max_length=255,unique=True,blank=True,null=True) class UserProfile(models.Model): acess_doctor_model = models.ForeignKey('hospital.Doctor', on_delete=models.CASCADE,blank=True,null=True,related_name="acess_doctor_model") ....my others model fields Now I need to access UserProfile model from my views fuction. here is my views.py def EditDoctor(request,slug=None): obj = get_object_or_404(Doctor,slug=slug) user_profile = UserProfile.objects.filter(acess_doctor_model=obj) print(user_profile) here is my perint result for user_profile : <QuerySet [<UserProfile: None>]> here is my print result for obj: Doctor_id: DCKMC3G0-----Doctor Name: HARTHO Why I can't get access userprofile model via this queryset: UserProfile.objects.filter(acess_doctor_model=obj) -
Different permissions for different methods in action decorator view?
I have an action decorator in a ViewSet that accepts two methods: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer = DefaultItemSerializer @action(detail=True, method=["get", "post"], permission_classes=[AllowAny]) def custom_action(self, request, pk): qs = self.get_object() if request.method == "GET": return Response(CustomItemSerializer(qs).data, status=200) else: serializer = CustomItemSerializer(qs, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.data, status=400) Currently both get and post have the same permission of AllowAny. What if I want them to be different? E.g. get to be AllowAny while post should only be IsAdminUser -
Why is Django forms fields value not rendering in html template for function based update view?
The issue is when i try to update my profile, i do not see the exising value i do not actually know what is wrong with the views.. views.py def profile_update(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() profile = get_object_or_404(Profile, user=request.user) Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=profile) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile', profile.user.username) else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Why Djano forms fields value not rendering in html template for function based update view?
This is my update views: def EditDoctor(request,slug=None): if request.method == "POST": obj = get_object_or_404(Doctor,slug=slug) form = DoctorUpdateFrom(request.POST,instance=obj) if form.is_valid(): form.save() return redirect('hospital:all-doctor') else: form = DoctorUpdateFrom() context = {'doctor_form':form} return render (request,'hospital/edit-doctor.html', context) The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms. -
Create new object Program and related objects Segments using data from another database and user provided fields
I am reading entries from an outside database using get_context_data and displaying them in a list. When user choses an entry - you get a form which displays the chosen entry's data via context. I want to create a model object based on what the user entered, and also create the related object(s) using the context data displayed on the form (not editable information). For example: You have a list of shows from the last month: Show-Dec-31 Show-Dec-30 Show-Dec-29 . . Show-Dec-1 When you choose a show (say Show-Dec-25): You get a form with Name: Show-Dec-25 - User can change this if they want Producer: _______ (required) Editor: ________ (required) Air Time: __:__:__ (required) Run Time: __:__:__ (required) Segments: (via context) (Display only) 1 Intro 00:01:00 2 Monologue 00:01:00 3 Dance Skit 00:09:00 4 Comedy Skit 00:09:00 Create Button Here When the user hits create - it creates a new Program in form_valid by saying: def form_valid(self, form): new_program = Program() new_program.title = form.name new_program.producer = form.producer new_program.editor = form.editor new_program.air_time= form.air_time new_program.run_time= form.run_time new_program.save() The segments need to be created - based off of the just created new_program id. So if new_program id after creation was 44 - then … -
Django Attach variables from one step to another
How would I grab the 2nd form and add it to the first form and save it in another model that looks the same as the custom user. etc username,password,email,first_name,last_name,verified Would I need to add another model? With a similar signup form? I would like another table that's not capable of logging in until the admins adds it to the abstractuser table. So adding users will also need to check if there are values in the new table. views.py from django.core.files.storage import FileSystemStorage import os from django.conf import settings class DoctorWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor')) template_name = "registration/signup.html" form_list = [SignUpForm,verify] def done(self, form_list, **kwargs): data=process_data(form_list) return redirect('home') class UserWizard(SessionWizardView): template_name = "registration/signup.html" form_list = [ SignUpForm] def done(self, form_list, **kwargs): data=process_data(form_list) form_list[0].save() userCreate = form_list[0] username = userCreate.cleaned_data.get('username') raw_password = userCreate.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(self.request, user) return redirect('home') forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class verify(forms.Form): verified = forms.ImageField(required=True) class Meta: model = Profile fields = ('verified',) models.py class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True) phone_number = PhoneNumberField(max_length=25, region="US") … -
VACUUM is not reducing the database size
I am using an sqlite database with Django. The db.sqlite3 file is currently 600KB, while the database is really small, so I think it should fit in just a few KB. After deleting some more rows, I executed: sqlite3 db.sqlite3 "VACUUM;" However, the file did not become a single byte smaller. The environment is the console of pythonanywhere. What am I missing? -
Selective loading of values to populate the ModelViewSet form / Phyton Django RestFramework
I admit I'm new to the Python world. I would like to add some loading moments while I compile the form of the Rest Framework ModelViewSet, in order to make the insertion of data in the forms more agile. below also 2 screens of the form generated by the Framework and a screen of the models, I think I'm working well, I made them in ForeingKeys Is it possible to make such customizations in the Rest Framework views? Rest Framework View Screenshot Django Models -
How extract array values and save to variable? Python
I dont understand how this line of code works in the function below. Mainly what I am asking is how is this line capturing any data? What is this method of capturing data called? Problem line below? self.cart[product_id]['quantity'] = quantity Full function below? def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() -
(python) How do i split a csv with /n if the fields have strings with /n inside
I'm having trouble splitting a csv because some of the fields have a "\n" inside them i'm using: file_data = csv_file.read().decode("utf-8") csv_data = file_data.split("\n") but the fields look something like 'string 1','string 2', 'string 3' 'string 4', i would like csv_data[0] to be strings 1 and 2, csv_data[1] to be string 3, and csv_data[2] to be string 4 the way i'm currently using, i get csv_data[0] correctly, but string 3 is split in two indexes since it has a /n inside it's text... -
Related name returning post.commentpost.none
Can anyone explain me, why i get Post.CommentPost.None? How to correct connect CommentPost with Posty in query? I need get {{posty.comments.user}} my result is Post.CommentPost.None Here something about my models and functions. class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) likes = models.ManyToManyField(Profil, related_name='liked') unlikes = models.ManyToManyField(Profil, related_name='unlikes') created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE) test_wyswietlenia = models.IntegerField(default=0, null=True, blank=True) class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) VIEWS tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.prefetch_related('comments') my_view = Posty.objects.prefetch_related('my_wyswietlenia') else: my_tag = Posty.objects.filter(created_tags__tag=tag) my_view = Posty.objects.prefetch_related('my_wyswietlenia') TEMPLATES {% for post in my_tag %} {% if post.comments.last.user == None %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">Brak komentarza</a></span><br/> <span class="forum_tag_author">Stworzony przez » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">{{post.author}} </a> </span><hr/> {% else %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">{{post.comments.last.content1}}</a></span><br/> <span class="forum_tag_author">Odpowiadający » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">Dodany przez: {{post.comments.last.user}} </a> </span><hr/> {% endif %} {% endfor %} And this {{post.comments}} … -
Why do I get NameError: name '_' is not defined when setting custom templates for djangocms-video?
I am trying to get custom templates working for djangocms-video. So far there is a fresh djangocms project set up with some bootstrap and running fine. According to the readme we would need to specify this in the settings.py to make a custom template available (in this case a template named "feature"): DJANGOCMS_VIDEO_TEMPLATES = [ ('feature', _('Featured Version')), ] After setting this and running manage.py this error comes up: ('feature', _('Featured Version')), NameError: name '_' is not defined According to other threads we would need to import gettext like this in the modely.py: from django.utils.translation import gettext as _ or like this: django.utils.translation import ugettext_lazy as _ No luck so far. What am I missing here? Here is some info on the environment: python --version Python 3.9.2 pip list Package Version -------------------------- ----------- asgiref 3.4.1 cssselect2 0.4.1 dj-database-url 0.5.0 Django 3.1.14 django-classy-tags 2.0.0 django-cms 3.8.0 django-filer 2.1.2 django-formtools 2.3 django-js-asset 1.2.2 django-mptt 0.13.4 django-polymorphic 3.0.0 django-sekizai 2.0.0 django-treebeard 4.5.1 djangocms-admin-style 2.0.2 djangocms-attributes-field 2.0.0 djangocms-bootstrap4 2.0.0 djangocms-file 3.0.0 djangocms-googlemap 2.0.0 djangocms-icon 2.0.0 djangocms-installer 2.0.0 djangocms-link 3.0.0 djangocms-picture 3.0.0 djangocms-style 3.0.0 djangocms-text-ckeditor 4.0.0 djangocms-video 3.0.0 easy-thumbnails 2.8 html5lib 1.1 lxml 4.7.1 Pillow 9.0.0 pip 21.3.1 pkg_resources 0.0.0 pytz 2021.3 pytz-deprecation-shim 0.1.0.post0 reportlab … -
How to use work week in DateField in Django admin
In my model, I say: class Foo(models.Model): start = models.DateField(help_text='Start Date') In the django admin, when adding a new Foo object, I see a text field with a calendar attached allowing me to select the date. I want to customize this a little bit so that I can either select the date from the calendar or enter something like WW12'22 in the textfield and during Save, this gets converted into a DateField. I am not sure how to do implement this in the django admin. Any ideas would be helpful. -
How to call a js folder inside Django static folder from an html file inside its own folder
I have a question using django 3.2.10. I can't download my js file which is inside js folder, also inside static folder. Additionally, I have a folder called views where there are my html files, they are organized by webapp name. I am calling a js file (perbd.js) from perbd.html. This is the structure of my project. This is the line in my perbd.html: <script type="text/javascript" src="{% static 'js/perbd.js '%}" ></script> And I have these lines in my Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) The point is that It doesn't work my js. I have the snapshot from the firework inspector: The files which have %20 in the end, they are not working. I don't know what does it mean? Also I attach the image from the firefox console: I'm thinking that it could be the folders organization because perbd.html is inside persona folder. I really appreciate all your help. Thanks in advance. -
Wagtail & Django issues
I just updated from Wagtail 2.11.2 to 2.15.1 and Django 2.2.6 to 3.0. Everything works locally but when I deploy and visit the cms I get an internal server error. The error in django_errors.log is: Internal Server Error: /cms/ Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/test/utils.py", line 96, in instrumented_test_render return self.nodelist.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/template/loader_tags.py", … -
Django "[object] instance with id X does not exist" error when creating/updating object foreign key in admin, using sites framework
I have a Django application using the sites framework. I have a Category model and a Topic model. The Topic model has a "category" attribute pointing to a specific Category object. Both of these models have "site" attributes linking them to specific sites in the Django application. All of these websites are hosted on the same server. What I'm noticing is that, when I create/update an object (Topic) in the admin - and set the topic's foreign key field (category) to a category that is not on the site configured in the SITE_ID setting - I get this error message: category instance with id X does not exist When I change the SITE_ID in settings.py, I can now set the topic's category to a category on that site, but not on any other sites. Here's a chart to help you visualize this: flow chart There are two relevant models here, Category and Topic: class Category(models.Model): name = models.CharField(max_length=128) slug = models.SlugField() description = RichTextUploadingField( blank=True, default='', verbose_name='Category Description', help_text='''Category description to be displayed on category page goes here''' ) site = models.ForeignKey(Site, on_delete=models.CASCADE) on_site = CurrentSiteManager() objects = models.Manager() class Meta: verbose_name_plural = 'categories' ordering = ['name'] class Topic(models.Model): site … -
Django database relation
I am working on a forum using django, I have a problem accessing user fullname and bio, from a model class I have. I have no problem accessing the user.username or user.email, but not from the Author class.. This is from the models.py in the forum app User = get_user_model() class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=40, blank=True) slug = slug = models.SlugField(max_length=400, unique=True, blank=True) bio = HTMLField() points = models.IntegerField(default=0) profile_pic = ResizedImageField(size=[50, 80], quality=100, upload_to="authors", default=None, null=True, blank=True) def __str__(self): return self.fullname My form is in the user app, where i have a profile update site, and the form is like this from forums.models import Author class UpdateForm(forms.ModelForm): class Meta: model = Author fields = ('fullname', 'bio', 'profile_pic') Then here is some of the update site, however nothing let me get access to the bio or fullname, I've tried so many combos. and I am lost here.. {% block content %} <section class="section" id="about"> <!-- Title --> <div class="section-heading"> <h3 class="title is-2">Hey {{ user.username }}</h3> <div class="container"> <p>{{ user.bio }}bio comes here</p> </div> </div> If there is some relation i am missing please help