Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove duplicates in django /postgres while the primary key is a String
In the below table, id is my primary key , The item A with date 2021/07/22 is duplicated in the below , I want that to be removed. In short the combination of item and date should be unique id item date price qwtywte A 2021/07/22 102 afdsgfg B 2021/07/22 210 hgasdah A 2021/07/22 102 basjhjs A 2021/07/21 114 vsjdsjg B 2021/07/21 250 I am ok with solution from sql query or in django ORM query -
Django Elastic Beanstalk Deployment Error Due to INSTALLED_APPS in Settings
I'm deploying a Django application through the Elastic Beanstalk CLI but have an error with an app I include in the INSTALLED_APPS in the settings.py file. Here's the layout of my django project: django3 |--- manage.py |--- requirements.txt |--- .ebextensions |--- 01_python.config |--- appone |--- migrations |--- __init__.py |--- templates |--- index.html |--- __init__.py |--- admin.py |--- apps.py |--- forms.py |--- models.py |--- tests.py |--- urls.py |--- views.py |--- django3 |--- __init__.py |--- asgi.py |--- settings.py |--- urls.py |--- wsgi.py When I run the django project locally everything works fine, but when I attempt to deploy to Elastic Beanstalk I get this error: ModuleNotFoundError: No module named 'appone' This is preceded in the logs at some point with these lines: apps.populate(settings.INSTALLED_APPS) app_config = AppConfig.create(entry) so it seems it's attempting to make an entry for the appone app but the name for it in the apps.py I have is incorrect. My apps.py file is this: from django.apps import AppConfig class ApponeConfig(AppConfig): #default_auto_field = 'django.db.models.BigAutoField' name = 'appone' And my settings.py file INSTALLED_APPS is this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appone' ] I found some similar issues like this one: Django : Can't import 'module'. Check that module … -
Open source professional networking platforms like "LinkedIn" or "Xing"
Which open-source professional networking platforms like "LinkedIn" or "Xing" which built on using new technologies (Not PHP/WordPress). Open source should be built in the new latest technology that saves time and manpower efforts during customization, fast loading, database connectivity, etc. I would greatly appreciate it if you kindly give me some suggestions on this research data. -
Django Rest framework why to use [closed]
I want to know why to use Django rest framework even though I can use normal models print("hello world") -
Django rest framework: serializer does not include id field in response data
I am learning Django rest framework and have created the following serializer: class EventCreateSerializer(serializers.ModelSerializer): organiser = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Event fields = ['id', 'name', 'description', 'date', 'organiser'] def save(self, **kwargs): name = self.validated_data['name'] description = self.validated_data['description'] date = self.validated_data['date'] organiser = self.data['organiser'] organiser_account = Account.objects.get(username=organiser) if not organiser_account: raise serializers.ValidationError('Error setting the organiser field') event = Event.objects.create(name=name, description=description, date=date, organiser=organiser_account) event.save() return event Notice how 'id' is included as a field. Now I have the following view: class EventCreateView(APIView): permission_classes = [IsAuthenticated] def post(self, request, format=None): context = { 'request': self.request } serializer = EventCreateSerializer(data=request.data, context=context) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'fail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) So when I make a post request to the appropriate url, I get back a response that include serializer.data. However, this does not contain the 'id' field (but it does contain the other fields). The model used has an automatically generated id field. I want the response to include the id field, how can I achieve this? -
Integrating a plugin in netbox
I am creating a plugin in netbox. I have run the setup.py file below as prescribed by the documentation from setuptools import find_packages, setup setup( name='netbox_ipdevcir_plugin', version='0.1', description='A plugin to add many2many models for IP Address, Device and Circuits', url='https://gitlab.openaccess.com', author='Author', license='Apache 2.0', install_requires=[], packages=find_packages(), include_package_data=True, zip_safe=False, ) and have gotten the following: root@username:/opt/netbox/netbox/netbox_ipdevcir_plugin# python3 setup.py develop running develop running egg_info writing netbox_ipdevcir_plugin.egg-info/PKG-INFO writing dependency_links to netbox_ipdevcir_plugin.egg-info/dependency_links.txt writing top-level names to netbox_ipdevcir_plugin.egg-info/top_level.txt reading manifest file 'netbox_ipdevcir_plugin.egg-info/SOURCES.txt' writing manifest file 'netbox_ipdevcir_plugin.egg-info/SOURCES.txt' running build_ext Creating /usr/local/lib/python3.8/dist-packages/netbox-ipdevcir-plugin.egg-link (link to .) netbox-ipdevcir-plugin 0.1 is already the active version in easy-install.pth Installed /opt/netbox/netbox/netbox_ipdevcir_plugin Processing dependencies for netbox-ipdevcir-plugin==0.1 Finished processing dependencies for netbox-ipdevcir-plugin==0.1 root@username:/opt/netbox/netbox/netbox_ipdevcir_plugin# I have then created models which i want now need to sync through the command ./manage.py makemigrations netbox_ipdevcir_plugin and i am getting (venv) root@username:/opt/netbox/netbox# ./manage.py makemigrations netbox_ipdevcir_plugin Traceback (most recent call last): File "/opt/netbox/netbox/netbox/settings.py", line 613, in plugin_config = plugin.config AttributeError: module 'netbox_ipdevcir_plugin' has no attribute 'config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/base.py", … -
How to use Django/Rest Framework to search a database table without specifying a column?
Initial question: Following the Django documentation, to get a QuerySet of blog entries from the year 2006, we can use filter() like so: Entry.objects.filter(pub_date__year=2006) Retrieving specific objects with filter, it is assumed that we know which column to search in. How can we search for an object if we do not know which column it could be in? For a small number of columns, we could chain the filters like so: Entry.objects.filter(column1='foo').filter(column2='foo') With +30 columns, this seems highly repetitive. What is a better way of doing this? A follow up question: Given that in urlpatterns we find the following path: path('foo/bar/<str:object>/', views.ViewObject.as_view()) And ViewObject uses the Rest Framework generic views: class ViewObject(generics.RetrieveUpdateDestroyAPIView): serializer_class = ObjectSerializer ... queryset = ? How can we construct the ViewObject view such that parameter <str:object> is used to search for a value in all columns of a database table? -
Django Restframework with nested json
Iam using Django with Restframework. Iam trying to get a json output from serializers in a nested manner with key as one of the fields from model. I acheived the nested JSON but the json key for them is troubling me. Here is my code and expected results out of it: Models.py class Tags(models.Model): tagId = models.CharField(primary_key=True, max_length=100, default=1) section = models.CharField(max_length=100,default=1) def __str__(self): return self.section class TagItem(models.Model): section= models.ForeignKey(Tags, on_delete=models.CASCADE,default=1,related_name="items") select = models.BooleanField(default=False) name = models.CharField(max_length=50) def __str__(self): return self.name serializers.py class TagItemModelSerializer(serializers.ModelSerializer): class Meta: model = TagItem fields = '__all__' class TagModelSerializer(serializers.ModelSerializer): items = TagItemModelSerializer(many=True) class Meta: model = Tags fields = ['pk','section', 'items'] Expected output: { "crafts" : { //craft is comming from Tag model's "section" "id": 1, "section": "crafts", "items": [ { "id": "10", "select": false, "name": "Wood", "category": "crafts" }, ] }, "states" : { "id": 2, "section": "states", "items": [ { "id": "20", "select": false, "name": "Andhra Pradesh", "category": "states" } ] }, "others" : { "id": 3, "section": "others", "items": [ { "id": "30", "select": false, "name": "Volunteer", "category": "others" } ] } } Current output: [ //cant get the key of Tag model's "section" { "pk": "1", "section": "states", "items": [ { … -
My form redirects the page to the API url used on the form (action="some url") after submitting, how to fix this? Django VanillaJS
This is what my page looks like: I have a sidebar which can change the contents of the page depending on the button clicked. When I click on About the page will look like this: So I made this with Vanilla JS using inner.HTML. PROBLEM: When I refresh the page, meaning the inner.HTML is not happening yet because I never clicked any buttons on the sidebar yet. My form submits properly and it does not redirect me to the API url used on the form. But, when I tried to click the About button and click Home button and try to submit the form again, it redirects me now to the API page used on the form. My guess is, there is something wrong with my vanillajs using inner.HTML. CODE looks like this: HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block script %} <script type="text/javascript" src="{% static 'js/cms/cms.js' %}"></script> {% endblock %} {% block style %} <link rel="stylesheet" type="text/css" href="{% static 'css/cms.css' %}"> {% endblock %} {% block content %} <div class="container"> <div class="sticky-sidebar-page"> <div class="sidebar"> <h3>Manage Site Contents</h3> <div class="list-group"> <button class="list-group-item list-group-item-action active" aria-current="true" onClick="showHomeContent()" id="homeButton">Home</button> <button class="list-group-item list-group-item-action" aria-current="true" onClick="showAboutContent()" … -
Django: Can't save file to FileField
According to Django Docs, I'm trying to save File or ContentFile to FileField. When I access FileField it doesn't give me a FieldFile proxy, so I don't have a save method like all examples. Can I use djangonic :) way to solve this? (Django 3.2) Model: class Report(InModelFileStorageMixin, models.Model): ... class InModelFileStorageMixin: file = models.FileField( _('Report File'), blank=True, null=True, ) My exception is: ipdb> obj.file.save *** AttributeError: 'FileField' object has no attribute 'save' -
How to avoid Django NoReverseMatch Error?
I am confused with Django redirect. The idea is to redirect users to an external URL, but I always get the NoReverseMatch Error. My urls.py from django.urls import path from . import views from django.views.generic.base import RedirectView path('home', views.home_view, name="home"), # redirect user from home to go-to-django path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'), # some dummy url my views.py from django.urls import reverse from django.shortcuts import redirect, render def home_view(request): return redirect(reverse('go-to-django')) -
Django - multiple queries with pagination
After updating from Django 1.9 to 3.2.5 my advanced search function doesn't work with pagination anymore. I have two search functions. One which is always available in the header to search for project names and is included in my base.html template. The other one is an advanced search function which allows to search for specific criterias e.g. department, project name, status, etc. all works fine as long as there is no pagination. the normal search function works with pagination but the advanced doesn't. The problem seems the return of the query, which returns one list for mutliple queries starting with q=['','','']. Because my form fields in my advanced search have different names e.g. qD,qS, etc. the parts of the list can't be properly assigned. url return when doing advanced search before changing page: http://127.0.0.1:8000/advanced_search/?csrfmiddlewaretoken=rzIvrOJdUMHwwxaSR18hy48mPTNCORXjaMYigqELXKRlKzNhBpEjbVSueQGHs7yl&qD=corporate&qC=&qN=&qT=&qS=&qA=&qCD= url return when doing advanced search after changing page: http://127.0.0.1:8000/advanced_search/?page=2&q=(None,%20%27corporate%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27) here my django and html code: views.py # normal search def search(request): template = 'MAR_Projects/projects.html' query = request.GET.get('q') if query: filtered_projects = table_projects.objects.filter(Q(Project_Code__icontains=query) | Q(Project_Name__icontains=query)) else: filtered_projects = table_projects.objects.all().order_by('-Project_Creation') searchResultCount = filtered_projects.count pages = pagination(request, filtered_projects) context = {'items': pages[0], 'page_range': pages[1], 'query': query, 'searchResultCount':searchResultCount } return render(request, template, context) #advanced search def advanced_search(request): template = … -
The complaints on the view complaints page are not showing up
I am creating a complaint management system where users can enter their complaints as well as view and edit them and also view other users complaints. On the page where the users can view others complaint, no complaints or data is showing up. What do I do? This should be showing up : But this is what is showing up: My models.py: class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "msi.jpg", null = True, blank= True, upload_to= 'static/profileimages') first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = … -
Django makemigrations show no changes detected after table rename in mysql
I have a Django application with a My-SQL database. recently I alter the table_name with the help of MySQL query in the MySQL-shell, after this when I run makemigration and migrate command terminal says "No changes detected". how can i reolve this issue and create again this table with help of django makemigration and migrate. -
how to change booleanfield to use bootstrap switch toggle
I want to change booleanfield model to use bootstrap switch toggle. # model blank_on_off = models.BooleanField(default=False) If i click on the button like above, then blank_on_off which is false changes to true and if i click one more time then changes again false. I think I should use JavaScript, how should I approach it? Thanks. -
DateTime picker in pure Django
I need to have a picker for DateTimeField, but I dont really know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': forms.widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}. time_attrs={'type': 'time'})} It shows me a working picker, but when I try to press save button it says me an error: AttributeError: 'list' object has no attribute 'strip' -
Why serialization in djano rest framework is costly in terms of performance?
class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() serializer_class=SalesDataSummarySerializer response = writeSerializedDataToCSV(response, headers, fieldnames,serializer_class.data) I am trying to convert response into csv and it takes around 5 minutes for 25k records, Where as the below code takes around 15-18 seconds, Here I am manually looping and creating a json. class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() queryset_list=[] for data in queryset: queryset_dict={} queryset_dict['number']=data.number queryset_dict['name']=data.name queryset_dict['time']=data.time queryset_dict['code']=data.code queryset_dict['uuid']=data.uuid queryset_list.append(queryset_dict) response = writeSerializedDataToCSV(response, headers, fieldnames,queryset_list) -
Combine the huge amount of model in Django Rest
I have 2 models and an abstract class of model. models.py class TimeStampedModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField( verbose_name='Created At', auto_now_add=True ) is_deleted = models.BooleanField(default=False) modified = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(null=True, blank=True) objects = NoDeleteManager() objects_with_deleted = models.Manager() class Meta: abstract = True ordering = ['created_at'] class ScentData(TimeStampedModel): name = models.CharField( max_length=64, blank=False, null=False, # unique=True, default='' ) class RawData(TimeStampedModel): scent = models.ForeignKey( 'ScentData', on_delete=models.CASCADE, related_name='rawdata_scent' ) # sensorvalue store as dicttionary # Example: {"s1":1, "s2":2, "s3":3} sensorvalue = JSONField() But now I want to combine the sensorvalue that has the same scent of RawData and delete the RawData that already combined. """ Example: after combine the value of sensorvalue will be store as list [{"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, ...] """ sensorvalue = JSONField() I have written the ViewSet to combine the RawData. Because I have 10M of rows, so my server can not handle the big times to execute. views.py class ScentDataViewSet(viewsets.ModelViewSet): queryset = ScentData.objects.all() @action(detail=False, methods=['GET'], url_path="combine_rawdata") def combine_rawdata(self, request, pk=None, **kwargs): scent_data = ScentData.objects.all() list_rawdata = list() for scent in scent_data: # call rawdata that has same scent using related_name all_rawdata = scent.rawdata_scent.all() # put all sensorvalue in list … -
Django getting related objects maintaining parent's order in a queryset
I have the following structure in a django application class Course(models.Model): name = models.CharField(_("Course Name"), max_length=50) class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(_("Module Name"), max_length=50) number = models.IntegerField(_("Module Number")) class Chapter(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE) name = models.CharField(_("Chapter Name"), max_length=50) number = models.IntegerField(_("Chapter Number")) I wanted to fetch all Chapters that is contained in a course, with the order of the module (based on module number) and the order of chapter ( based on chapter number ) for example the hierarchy can be like this Course 1 has Module 1 -- Chapter number=1 (1.1) -- Chapter number=2 (1.2) -- Chapter number=3 (1.3) Module 2 -- Chapter number=1 (2.1) -- Chapter number=2 (2.2) -- Chapter number=3 (2.3) Course 2 has, Module 1 -- Chapter 1 -- Chapter 2 -- Chapter 3 Module 2 -- Chapter 1 -- Chapter 2 -- Chapter 3 I would like to fetch All chapters in Course 1 such in the order [ (1.1), (1.2), (1.3), (2.1), (2.2), (2.3) ] and so on... When i fetch all chapters with the query Chapter.objects.filter(module__in=Course1.module_set.all()) I'm getting the chapters ordered by [ (1.1), (2.1), (1.2), (2.2), (3.1), (3.2) ]... As the chapter number is 1 2 3 etc... … -
Filtering Characters in HTML - Python - Django
So I am building a website and needed to be able to filter by a prefix on a model field I have in Django on my website. Now when I display this I need the prefix to be gone. The simplest way to do this seems to be in the HTML itself with something that says to not include the first 4 characters or before such as [4:]. This seems simple but I can't get it to work and I can get this to work |truncatechars:"10" which was a recommended solution. I need something in either my views or in my HTML that says when you print don't display the first 4 characters but display everything beyond that. Thanks for any help! HTML: {{ form.title }} Models: class DocPost(models.Model): user = models.ForeignKey(User, default=True, related_name="Doc", on_delete=models.PROTECT) title = models.CharField(max_length=100) content = HTMLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pk'] def __str__(self): return self.title def get_absolute_url(self): return reverse('doc-post-list') Django Views: def docpostnewview(request, pk): obj = get_object_or_404(DocPost, id=pk) form = DocPostForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context = {"form":form} #context['title'] = DocPost.objects.all().filter(title='title') return render(request, "my_app/use_template.html", context) -
Can a custom manage.py command know the server domain?
I'm writing a custom manage.py command, and I need the base URL of the site. Is it possible to dynamically determine it, or do I have to hardcode it somewhere? I tried using django.contrib.sites.shortcuts.get_current_site, but it needs a request. I found this example to "get site without request": from django.contrib.sites.models import Site current_site = Site.objects.get_current() but I get this error: RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I'm not sure what I should put in INSTALLED_APPS to make this work. Should I do something completely different? Or it this not even possible? -
How to set db model fields to just read-only even a superuser should be able to edit it
I tried this way like we do with primary keys But it's not working they as I want. I want Some fields to not editable from Django Admin We can manage it with permissions but I want it for all even superuser shouldn't be able to change values I tried this way #models.py class Payments(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name="Payment Made By",) paymentForOrderID = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Payment For Order ID") paymentMethodUsed = models.CharField(max_length=200, null=True, blank=True, verbose_name="Method Used") aproxTimeAndDateOfPayment = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Approx Date/Time Of Payment") totalAmountPaid = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Amount Paid") paymentDetails = models.TextField(null=True, blank=True,editable=False,verbose_name="Details") createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True,editable=False, verbose_name="Entry ID") def __str__(self): return str(self.createdAt) Doing this when I open it it only shows editable fields but not the others. -
Retrieving None as an entry_set django
profile class SeekerProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) current_salary = models.IntegerField() currency = models.CharField(max_length=25) photo = models.ImageField(upload_to='applicants') resume = models.FileField(upload_to='applicants/documents') def __str__(self): return self.user.first_name Skillset model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' But when i am trying to get the entry set i am receiving None even though i am clearly having entries for amir >> from seekerbuilder.models import SeekerProfile >>> obj = SeekerProfile.objects.get(id=1) >>> print(obj) amir >>> print(obj.seekerskillset_set) seekerbuilder.Seekerskillset.None >>> for val in obj.seekerskillset_set: ... print(val) ... Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'RelatedManager' object is not iterable >>> -
What is the correct settings for static files in django
I just started using django and I got confused over the static files. As per this post correct static files setting I understand that STATIC_URL is just like the name. STATICFILES_DIRS is the place where django will look for static files and STATIC_ROOT where the static files will be collected to. For my project I had the following file sys rest |__ rest |__ settings.py pages static |__admin |__images |__vendor |__bootstrap templates manage.py I decided to go for a project based approach when having my folders instead of a per app one. Some stuff was not working with the website landing page I had and I saw that I needed to collectstatic and so I did but I set the path to my already existing static file which did not let me at first but somehow ended up working. Out of nowhere my static folder had admin on it which I assume is from the admin app that comes with django, and my project finally started to work properly which is the confusing part. I decided to follow the post and included in my settings the following STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') … -
URL loading the wrong view - Django
Really struggling with this one. For some reason I can't get my URL to load the correct view. The site loads the home page correctly but then when I add on the extesion to acess another one of my apps, it just reloads the home page. It doesnt throw any errors or anything, it just wond direct to the correct page. This is my base URL file: path('admin/', admin.site.urls), path('', blog_views.home), path('<username>/', include('blog.urls')), path('community/', include('community.urls')), Start of the Blog URL file: path('', LogListView.as_view(), name='log'), This is the Blog views file: @login_required def home(request): user_name = request.user.username return HttpResponseRedirect(f'{user_name}/') class LogListView(LoginRequiredMixin, ListView): model = Post template_name = 'blog/log-main.html' login_url = 'login/' context_object_name = 'posts' ordering = ['-date_added'] def get_context_data(self, **kwargs): context = super(LogListView, self).get_context_data(**kwargs) context['posts'] = Post.objects.filter(user = self.request.user) return context The home function above sutomatically directs each user to thier specific home page by placing thier username at the start of the URL path. Then here is my Community app URL file: path('', CommunityListView.as_view(), name='community'), And the Community view file: class CommunityListView(LoginRequiredMixin, ListView): model = Post template_name = 'community/community.html' context_object_name = 'postss' ordering = ['-date_added'] def get_queryset(self): qs = super().get_queryset() active_user = self.request.user active_user_following = active_user.following.values_list('user_id', flat=True) following_user_objects = [] …