Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to set value to not displayed form field? 'WSGIRequest' object has no attribute 'seller'
I can not solve my issue. I need help, it will be really kind :) channel and consumer are automatically set thanks to the view "form.instance". But I don't know how to do the same with seller. Important, the page is dedicated to two user: seller and consumer. Only consumer can give a review. The page is a channel. So what's the best way to set automatically seller value? class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.channel.name views.py ... def form_valid(self, form): if form.is_valid(): form.instance.channel = self.object form.instance.seller = self.request.seller.userprofile.pk form.instance.consumer = self.request.user form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) forms.py class ChannelRatingForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(ChannelRatingForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("comment",css_class="form-control",style="margin-bottom:10px",rows="1"), Field("ratesugar",css_class="single-input"), ) self.helper.add_input(Submit('submit','Review',css_class="btn btn-primary single-input textinput textInput form-control")) class Meta: model = Rating widgets = { 'comment':forms.TextInput(attrs={'class':'','style':'','placeholder':'What a cook!'}), } fields = [ 'comment', 'ratesugar', ] -
Python Script Nor Running In PythonAnywhere
I am working on a Django project. It includes a functionality in which when admin clicks on a certain button, it runs a Python script and redirect it to some other page after complete process. Before hosting, it was working fine. Now that I hosted it here, the script doesn't run at all. It just redirects to another page without providing any error. Why's that? Also, my script includes chromedriver, in case it has anything to do with it. Kindly help me. This might be the error. Why doesn't it recognize it? Code out = run([sys.executable, '//home//maisum279//traffic//traffic//trafficapp//traffic.py', "--domain", url, "--threads", '5', "--max-clicks", maximum, "--min-clicks", minimum, "--stay", stay, "--requests", requests]) Server Log 2020-09-21 11:05:02 /usr/local/bin/uwsgi: unrecognized option '--domain' 2020-09-21 11:05:02 getopt_long() error The script is in Python, but now it seems to be running with uswgi. What can I do make it work? Please help. -
cannot unpack non-iterable bool object(when trying to filter result for user registered in auth>User module)
I’m Creating One django based web app and I have used Auth> User model(without any customization except password hiding) and for user detail I have created another model ChangeShift and model based form. case1: when i am using alluser = ShiftChange.objects.all()i'm able to see all the data available in ShiftChange model. Case2: Now i want that when user is logging he should be able to see data related to his name and i'm using def retrieve_view(request): # alluser = ShiftChange.objects.all() alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) return render(request, 'apple/shift2.html', {'alluser': alluser}) for this i am getting error: cannot unpack non-iterable bool object Please find the below Trace [21/Sep/2020 11:13:18] "GET /static/css/auth.css HTTP/1.1" 404 1662 Internal Server Error: /alldata/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shaileshyadaav/djangoshaileshdurga/mapsIT/apple/views.py", line 53, in retrieve_view alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, … -
Django upload image using page slud/id
I'm trying to add the ability to upload an image to a post but having issues. The image field is in its own model but uses a foreign key to show which post it relates to. At the moment the upload button does not post the form but also how would I use the post page url/slug/id as the image foreign key. Would i need to call it in the html post page? views.py def designUpload(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'users/dashboard.html') else: form = ImageForm() return render(request, 'users/dashboard.html', { 'form': form }) **models.py** class Designs(models.Model): forbrief = models.ForeignKey(Brief, on_delete=CASCADE) postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True) design = models.ImageField(null=True, blank=True) date = models.DateTimeField(auto_now=True, blank=True) forms.py class ImageForm(forms.ModelForm): class Meta: model = Designs fields = ["design",] HTML Form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="image" name="mydesign"> <button type="submit">Upload</button> </form> -
Django braces PermissionRequiredMixin raise 403 forbidden even on assigned permission
I'm working on a django(3) project in which I have a Course model and on signup I'm assigning the permission to Can add course but when I hit the the CourseCreate view which is using PermissionRequiredMixin it returns 403 forbidden Here's my code: User registration view: if request.method == 'POST': print('get post req') if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() if form.cleaned_data['is_instructor'] is True: permission = Permission.objects.get(name='Can add course') instructor_group = Group.objects.get(name='instructor') user.groups.add(instructor_group) user.user_permissions.add(permission) return HttpResponseRedirect(reverse_lazy('users:login')) else: print(form.errors) CreateCourse View: class CreateCourse(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Course fields = ['title', 'subject', 'slug', 'overview', 'course_image'] template_name = 'courses/create_course.html' permission_required = 'courses.add_course' login_url = reverse_lazy('users:login') raise_exception = True I confirmed in admin that the permission is selected for the user successfully. -
How send table with form?
How i can send my table on server? I do not need html code, i want send only table data. This is my table: <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> </table> This is my form: <form action="/actionpage" method="post"> <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname"><br><br> // How? **<label for="table">Table Rows</label> <input type="text" id="table" name="table"><br><br>** <input type="submit" value="Submit"> </form> How i can paste my table in form? May be exists special tag like a INPUT? -
upload file and other attributes with AJAX django
I want to upload my file with some other attributes using AJAX My AJAX code: var file = $('#uploaded-file').get(0).files[0] if (file != null) { var reader = new FileReader() reader.onload = function () { var filedata = reader.result; $.ajax({ url: '/upload_file', type: 'POST', dataType: 'json', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, data:JSON.stringify({'data':filedata, 'name':file.name}), success: function (response) { console.log(response) }, error: function (response) { console.log(response) } }) }; reader.readAsArrayBuffer(file) } My Djnago view.py: def upload_file(request): print(json.loads(request.body)) return JsonResponse({'response':'request done'}) however i am not getting file data in my request body {'data': {}, 'name': 'abc.csv'} what i am missing here? -
Django Google Authentication Doesn't Work
I'm trying to implement the simplest google authentication to my django portfolio website using 'social_django', but whenever I go to my login page I get the 404 error, I tried moving the urls from portfolio to my main app but it didn't work: Using the URLconf defined in MyPortfolio.urls, Django tried these URL patterns, in this order: portfolio/ [name='index'] portfolio/ login/ ^login/(?P<backend>[^/]+)/$ [name='begin'] portfolio/ login/ ^complete/(?P<backend>[^/]+)/$ [name='complete'] portfolio/ login/ ^disconnect/(?P<backend>[^/]+)/$ [name='disconnect'] portfolio/ login/ ^disconnect/(?P<backend>[^/]+)/(?P<association_id>\d+)/$ [name='disconnect_individual'] portfolio/ logout/ [name='logout'] admin/ The current path, portfolio/login/, didn't match any of these. Here is my settings.py : (only changes are included) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'portfolio', 'social_django' ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '**code here**' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '**code here**' LOGIN_URL = '/auth/login/google-oauth2/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_URL_NAMESPACE = 'social' My main app urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('portfolio/', include('portfolio.urls')), path('admin/', admin.site.urls) ] My portfolio app urls: from django.urls import path, include from django.conf import settings from django.contrib.auth.views import auth_logout from . import views app_name = 'portfolio' urlpatterns = [ path('', views.index, name='index'), path('login/', include('social_django.urls', namespace='social')), path('logout/', auth_logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout') ] Portfolio app views: from … -
wagtail pagination, django, wagtail, python
I would be very grateful if someone can help me out on this. I am developing a wagtail site but am short on configuring pagination which when clicking through (ie it just returns the page but not the results), so I have pagination working but when I click, it just returns the page number but does not return the actual model. My code is this: from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator class BlogIndexPage(RoutablePageMixin, Page): introduction = models.TextField( help_text='Text to describe the page', blank=True) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Landscape mode only; horizontal width between 1000px and 3000px.' ) content_panels = Page.content_panels + [ FieldPanel('introduction', classname="full"), ImageChooserPanel('image'), ] def children(self): return self.get_children().specific().live() def get_context(self, request, *args, **kwargs): context = super(BlogIndexPage, self).get_context(request, *args, **kwargs) all_posts = BlogPage.objects.descendant_of( self).live().order_by( '-date_published') paginator = Paginator(all_posts, 9) page = request.GET.get("page") try: posts = paginator.page(1) except PageNotAnInteger: paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context["posts"] = posts return context in my html I have the following: {% extends "base.html" %} {% load wagtailcore_tags navigation_tags wagtailimages_tags %} {% block content %} {% include "base/include/header-index.html" %} <div class="col-12"> {% if tag %} <p>Viewing all blog posts by <span class="outline">{{ tag }}</span></p> {% endif %} {% if page.get_child_tags … -
How to override handler404 and handler505 error in django?
How do i override the handler404 and handler505 error in django? i already change the DEBUG TRUE into False in my settings.py. this is my views.py def Errorhandler404(request): return render(request, 'customAdmin/my_custom_page_not_found_view.html', status=404) def Errorhandler500(request): return render(request, 'customAdmin/my_custom_error_view.html', status=500) this is my urls.py handler404 = customAdmin.views.Errorhandler404 handler500 = customAdmin.views.Errorhandler500 urlpatterns = [ ..... ] this is the error this is the documentation i follow https://micropyramid.com/blog/handling-custom-error-pages-in-django/ -
AWS CI CD with codepipline error - attached log
I'm trying to deploy a Django project with code pipleine what I've done : Created Elastic beanstalk env py version 3.6 eb-activity.log returns this error I tried running pip upgrade on the env pushing to git but that didn't fix it. Any suggestions ? :) [2020-09-21T08:53:56.134Z] INFO [19227] - [Application update code-pipeline-1600678386608-0fd34dae5393dbc6a31d126a16f4daabf6dc966d@6/AppDeployStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting appdirs==1.4.4 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl Collecting apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) (from versions: ) No matching distribution found for apturl==0.5.2 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) You are using pip version 9.0.1, however version 20.2.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-09-21 08:53:56,127 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (ElasticBeanstalk::ExternalInvocationError) caused by: Collecting appdirs==1.4.4 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using … -
Django REST Framework page_size per view is not working as expected
I'm using Django 2.2 and Django REST Framework The DRF settings are REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'tools.rest_framework.pagination.StandardResultsPagination', 'PAGE_SIZE': 10, } Where the pagination class is customised to remove the URL for next and previous page and use page number instead. class StandardResultsPagination(PageNumberPagination): def get_next_link(self): if not self.page.has_next(): return None return self.page.next_page_number() def get_previous_link(self): if not self.page.has_previous(): return None return self.page.previous_page_number() I have two views where I want to customise the number of records per page class DataCreateListView(generics.ListCreateAPIView): serializer_class = DataSerializer pagination.PageNumberPagination.page_size = 20 class DataMinimalListView(generics.ListAPIView): serializer_class = DataMinimalSerializer pagination.PageNumberPagination.page_size = 5 and URLs defined are urlpatterns = [ path('data/minimal/', views.DataMinimalListView.as_view()), path('data/', views.DataCreateListView.as_view()) ] But when I visit the path https://example.com/data/ It gives only 5 records instead of 20. But when I remove the page_size from the DataMinimalListView then it gives 20. -
How to autoformat django html template tags in vscode
I've started learning Django and I'm using vs-code. I'm facing problem in auto-indentation of Django template html tags. I've tried so many formatters and extensions, searched everywhere, but cannot find a prettier like formatter which can indent the Django-html file template tags. <div class="col"> {% if something.someval >= 0 %} <p class="card-text">Value: {{ object.value }}</p> {% else %} <p class="card-text">Value: {{ object.other_val }}</p> {% endif %} </div> I want this to be indented as: <div class="col"> {% if something.someval >= 0 %} <p class="card-text">Value: {{ object.value }}</p> {% else %} <p class="card-text">Value: {{ object.other_val }}</p> {% endif %} </div> Can anyone please point me to appropriate extension or option? Thanks! -
How to acces instance variables in python within the class?
I am trying to write a form in Django in which a ModelChoiceField filters its options in a query using some input arguments from the constructor. I somehow do not quite understand how instance variables are supposed to work in Python... How can I acces the value of self.prev_status_no outside of init? I get an unresolved refernce error. class ShoppingCartStatusChangeForm(forms.Form): def __init__(self, *args, **kwargs): self.prev_status_begin = kwargs.pop('prev_status_begin') self.prev_status_no = kwargs.pop('prev_status_no') super(ShoppingCartStatusChangeForm, self).__init__(*args, **kwargs) status = forms.ModelChoiceField( queryset=StatusDefinition.objects.all().filter( shc_or_po="ShC").filter( step_number=(self.prev_status_no + 1))) status_begin_date = forms.DateTimeField() comment = forms.CharField() -
Display maps with Django and manipulate data?
i didn't find any recourses about how can I display maps with my Django projects and work on them -
How to fix standard_init_linux.go:211: exec user process caused "no such file or directory" error?
I try to "dockerize" a Django app. I work on Windows 1O and my project will deployed on Linux server. I build/run my containers. But my web app is in a loop "Restarting (1). x second ago" I do docker logs id_web_container I got an error standard_init_linux.go:211: exec user process caused "no such file or directory" so error might come from my entrypoint.sh file because of path... but when looking my Dockerfile file, I first set a work directory, copy the entrypoint.sh in this directory and then execute the file... what is wrong? # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt # Copy the entrypoint.sh file COPY ./entrypoint.sh . # Copy the project's files COPY . . # Run entrypoint.sh ENTRYPOINT [ "/usr/src/app/entrypoint.sh" ] -
How to Link Models in Django? ForiegnKey vs Parent Linking
I want to link stdClass and stdDetails with schoolDetails in such a way that I can access stdClass and stdDetails via schoolDetails without rendering the whole models in the WebPage. Is foreign key best to do it? from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class schoolDetails(models.Model): sname = models.CharField(max_length=50) email = models.CharField(max_length=95) subdate = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=100) principal = models.CharField(max_length=150, default='') address = models.CharField(max_length=100, default='Nepal') estdate = models.DateField(default=timezone.now) numstd = models.IntegerField(default=0) url = models.URLField(max_length=200, default='') password = models.CharField(max_length=95) def __str__(self): return self.sname class stdClass(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=95) ssname = models.CharField(max_length=95) cList = models.CharField(max_length=95) def __str__(self): return self.cList class stdDetails(models.Model): ondelete = models.ForeignKey(schoolDetails, on_delete=models.CASCADE) username = models.CharField(max_length=100) password = models.CharField(max_length=95) stname = models.CharField(max_length=150, null=True) ssname = models.CharField(max_length=150, null=True) stadd = models.CharField(max_length=150, null=False) stcls = models.CharField(max_length=150, null=True) stfname = models.CharField(max_length=150, null=True) stmname = models.CharField(max_length=150, null=True) stfo = models.CharField(max_length=150, null=True) stadate = models.DateField(default=timezone.now) stpnum = models.CharField(max_length=95, null=True) stbdate = models.DateField(default=timezone.now) stpht = models.ImageField(max_length=500, upload_to='') #(""), upload_to=None, height_field=None, width_field=None, def __str__(self): return self.stname #datetime.datetime(2020, 6, 25, 2, 33, 57, 858649, tzinfo=<UTC>) -
Returning optimised queryset based off of request.user for private comments
I currently have a comments model, whereby users can submit comments to our system "privately". This is set as a Boolean field on the model level, abridged version of the model as follows: class Comment(AbstractUUIDModel, AbstractTimestampedModel, VoteModel): class Meta: db_table = 'comments.Comment' indexes = [ models.Index(fields=['uuid', 'id']), ] verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-created_datetime'] id = models.AutoField(_('ID'), primary_key=True) parent = models.ForeignKey('comments.Comment', null=True, blank=True, on_delete=models.CASCADE) owner = models.ForeignKey('authentication.User', null=True, on_delete=models.CASCADE) text = models.TextField(_('Description'), default='') private = models.BooleanField(_('Is Private?'), default=False) def __str__(self): return self.text def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) Essentially, the conceptual issue I am having is around my queryset filter logic. I want it such that if the request.user coming in to the system is the owner of the comment, then they can see their own "private" comments. Else, they can only see the comments where private is false. So, I need to somehow merge the following two querysets for serialization in DRF: queryset = obj.comment_set.filter(private=False) queryset = obj.comment_set.filter(owner=self.context.get('request').user) I believe I am overthinking this, and perhaps I can do something like: from django.db.models import Q queryset = obj.comment_set.filter( Q(owner=self.context.get('request').user) | Q(private=False) ) Using Q objects... -
Django url not working in one place despite same exact url working in the same page at other place
I am using a url at two different places but for some reason when the website contains only the first instance , it works perfectly but when I add another instance of the same link , the entire page is throwing error for some reason This is the part of the HTML page where I am using it : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% for item in cat_menu %} <a class="dropdown-item" href="{% url 'category' post.category|slugify %}">{{ item }} </a> {% endfor %} </div> These are the two views involved in the link class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-post_date'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryView(request, cats): #change later to proper sluggify for better efficiency category_posts = Post.objects.filter(category=cats.replace('-',' ')) return render(request, 'category.html', {'cats': cats, 'category_posts': category_posts}) And this is the url path('Category/<str:cats>', CategoryView, name="category") Everythings seems to be completely correct but still for some reason I am getting the following error when I am trying to run the server Reverse for 'category' with arguments '('',)' not found. 1 pattern(s) tried: ['Category/(?P<cats>[^/]+)$'] Error during template rendering <a class="dropdown-item" href="{% url 'category' post.category|slugify %}">{{ item }} </a> … -
Share Django models between docker images
In my docker-compose there are a Django image and a independent python image for a script. I am trying to use the Models from the django application in the script, but I don't know how to import the models from one image to another. My docker-compose services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db service: build: context: . dockerfile: service_Dockerfile depends_on: - web ports: - "5555:5555" What could be the way to approach...? networks?? some image imports?? -
if cookie does not exist redirect user external url django
I have BaseContext view and other templateView. Token is created inside the template. I also checking the token cookie exists if not I redirect user to this url--> https://testdomain.com/get_token?origin=http://localhost:8000 class BaseContext(View): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) request = self.request if request.COOKIES.get('token') is not None: token = request.COOKIES.get('token') bla bla bla return context else: return HttpResponseRedirect('https://testdomain.com/get_token?origin=http://localhost:8000') and I have another view which inherited from basecontext class Services(BaseContext, TemplateView): template_name = "services.html" def get_context_data(self, **kwargs): request = self.request context = super().get_context_data(**kwargs) context.update({'service_active': 'Active'}) return context When I tried to load page, I got an error, like this, 'HttpResponseRedirect' object has no attribute 'update' -
How use Relative Url in html in Django?
Creating Django application , In Navbar there 3 anchor tags. When I write direct href="user/register" in Html file, it works for only first click. Getting url like http://127.0.0.1:8000/user/register/ from here if I click on any navbar link url is getting like http://127.0.0.1:8000/user/register/user/register or http://127.0.0.1:8000/user/register/login Have a look to code ProjectFolder/urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homePage, name = "homepage"), path('uploadFiles/', include("uploadFiles.urls")), path('user/', include("login.urls")), ] AppFolder.py/urls.py from django.urls import path from . import views urlpatterns = [ path("register/", views.register, name = "register") ] AppFolder/Views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def register(request): if request.method == "POST": return HttpResponse("Working on database") else: return render(request, "login/Register.html") Navbar.html <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="user/register">Register</a> </li> <li class="nav-item active"> <a class="nav-link" href="login">Log In <span class="sr-only">(current)</span></a> </li> </ul> </div> -
Get Django filter from an sql query
I want to convert this sql select query to a django filter query : "SELECT certiInst.* FROM bcs_certificate_instance certiInst LEFT JOIN bcs_certificate_instance certificateInstance ON (certiInst.certificate_id = certificateInstance.certificate_id AND certiInst.last_scan < certificateInstance.last_scan) WHERE certificateInstance.last_scan IS NULL ORDER BY last_scan DESC") Who knows the exact drf query to write please ... thanks -
TypeError: argument of type 'WindowsPath' is not iterable - in django python
whenever I run the server or executing any commands in the terminal this error is showing in the terminal. The server is running and the webpage is working fine but when I quit the server or run any commands(like python manage.py migrate) this error is showing. `Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 21, 2020 - 12:42:24 Django version 3.0, using settings 'djangoblog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Python37\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Python37\lib\site-packages\django\utils\asyncio.py", line 24, in inner return func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable ` my manage.py file is provided below because the error mentioned something about manage.py file: #!/usr/bin/env python """Django's command-line utility for administrative … -
Integrating AWS Lambda with Django Signals and Postgresql RDS
I am wondering if I could trigger an AWS Lambda function using Django's post_save signal, or trigger an AWS Lambda function when a model is saved (just as Django's post_save signal does). Additionally, I would like to know some conventional ways of accessing and making changes to postgresql RDS in AWS Lambda functions. Any tips or suggestions will be greatly appreciated. Thank you!