Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unauthorized scope error in LinkedIn oAuth2 authentication
Instead of getting the login form, I am redirected to my callback url with the following params: https://www.linkedin.com/uas/oauth/authenticate?oauth_token=77--7d1ccb00-b690-4046-af61-2079bf8e65b1&oauth_callback=http%3A%2F%2Flocalhost%3A8000%2Faccounts%2Flinkedin%2Flogin%2Fcallback%2F I have looked at the url and put http://localhost/accounts/linkedin/login/callback as the redirect uri and i still get an error. Any ideas? -
why the django PasswordResetView throwing error?
I have just starting to import the Django's password reset views in my urls, I have imported as below. from django.contrib.auth import views as auth_views path('reset-password/', auth_views.PasswordResetView, name='reset_password'), I tried to open the url as http://127.0.0.1:8000/reset-password/ I get an error: TypeError at /reset-password/ __init__() takes 1 positional argument but 2 were given I mean I didn't even do anything extra and it is throwing the error. Nothing seems to be working for me. This is crazy. Django Version: 3.0.8 Any suggestions? Thank you, -
template does not exists Django and Heroku
Folks I am had this issue when I deployed my app in Heroku, when the app is running on localhost everything works well, but at the moment to deploy in Heroku it throwsme these errors, I think is related with template rendering in games.snippets, but I have check all and it seems to be ok Environment: Request Method: GET Request URL: https://tienda-videojuegos.herokuapp.com/ Django Version: 3.0.8 Python Version: 3.6.11 Installed Applications: ['games', 'users', 'carts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'django.contrib.humanize'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /app/templates/games/snippets/search.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/games/templates/games/snippets/search.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/carts/templates/games/snippets/search.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/games/snippets/search.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/games/snippets/search.html (Source does not exist) Template error: In template /app/templates/base.html, error at line 0 games/snippets/search.html 1 : {% load static %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> 8 : <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> 9 : <link rel="stylesheet" href="{% static 'css/style.css'%}"> 10 : … -
Django 404 object not found in DetailView only on unicode slugs and remote server
I've got a big problem with Django while moving from local to production server. Im using DetailView with slug url parameter. Some of the slugs consist of unicode characters (allow_unicode=True). On local server everything works fine but when I moved to production server all of the links with slugs that contained decoded(like %%) unicode characters are invalid - No object matches query. Local postgres has my local "Polish_Poland.1250" lang and the server one is "pl_PL.utf8" both UTF-8 encoding. I have no idea what produces such problem. Please send help! Here is my code models.py class Item(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_name = self.name slug = models.SlugField(max_length=120, unique=True, verbose_name='Slug', blank=True, allow_unicode=True) def save(self, *args, **kwargs): if not self.id: # setting shop ID id = 'IT'+str(uuid4().int)[:8] while Item.objects.filter(id=id): id = 'IT'+str(uuid4().int)[:8] self.id = id # setting slug for pretty url self.slug = slugify(self.name, allow_unicode=True) ...... # updating the slug when name is changed to avoid # unique blocking for slug if self.__original_name != self.name: self.slug = slugify(self.name, allow_unicode=True) urls.py urlpatterns = [ ... path('przegladaj/<str:category>/<str:slug>/', ItemView.as_view(), name='product_view'), ] views.py class ItemView(DetailView): model = Item template_name = 'shop/product_page/product_page.html' I'd be grateful for any tips or advices -
Listing all Orders in an Admin Website in Django
I am trying to build an Admin Control Panel different from the existing one in order to better view some of the orders made in an E-commerce Project. I am trying to list all the orders made to be in a list view but I am getting the following error: __init__() takes 1 positional argument but 2 were given I tried to fix it but I am not sure the root of it. Here is the view.py which is already working to be viewed by users class OrderList(LoginRequiredMixin, ListView): model = Order template_name = "user_orders.html" context_object_name = 'orders' paginate_by = 2 ordering = ['-ordered_date'] queryset = Order.objects.filter(ordered=True).order_by('-ordered_date') def get_queryset(self): return Order.objects.filter(user=self.request.user, ordered=True).order_by('-ordered_date') This is the view I am trying to create for admin only to consolidate the orders together @staff_member_required class Control_Order_List(ListView): model = Order template_name = "control_all_orders.html" context_object_name = 'orders' paginate_by = 2 ordering = ['-ordered_date'] queryset = Order.objects.filter(ordered=True).order_by('-ordered_date') def get_queryset(self): return Order.objects.filter(user=self.user, ordered=True).order_by('-ordered_date') Here is the urls.py app_name = 'newsletters' urlpatterns = [ path('', views.index, name='index'), path('newsletter/', control_newsletter, name="control_newsletter"), path('control_all_orders', Control_Order_List, name="control_all_orders"), ] -
Changing Format Of DatePicker Causes Validation Errors
I'm using a datetime picker where a user chooses a month (MonthPickerInput). models.py birthdayMonth= models.DateTimeField(null=True, default=now) forms.py widgets = { 'birthdayMonth': MonthPickerInput( options={ "showClose": False, "showClear": False, "showTodayButton": False, } ), } My imports <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script> [..main code block including datepicker..] <script type="text/javascript" src="{% static 'application/javascript.js' %}"></script> The user clicks on the form field, a calendar drops down and they select a month and year. This works fine however as the user is only selecting a month/year the day is always set to '1'. This is fine on the back-end, but on the front-end it is displayed like this 2020-03-01. I'd instead like it to be displayed like this March 2020. To do this I added a field to format in froms.py: widgets = { 'birthdayMonth': MonthPickerInput( options={ "format":"MMMM, YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } This works and displays correctly, however form validation always fails (whenever I submit the form the calendar input is highlighted red but with no error message). How can I change only the front-end display but leave the back-end in the original format so that my validation stops freaking out? I guess I'd need to use … -
How to get json object data fron Micrsoft teams about the meeting attendance?
The problem is a get the attendance of meeting from Microsoft teams meeting using API to convert it into data and to store in Django database. Now this problem can simply be solved using csv file provided by Teams, but I would like the process to be automated. -
How to customize Core Rule Set in WAF
I am using WAF with my Django app (on Elastic Beanstalk). I added the Core Rule set to my ACL rules. This is causing large POST requests to be blocked (which I need in my Django app). However, I do want the majority of the functionality in the Core Rule set to be applied (except for this rule). Is there any way I could edit the rules of the Core Rule set? Thanks! -
Django Create Model from ListView
I have a ListView to list instances of a model and I want users to be able to create a new instance from the same page. I tried multiple inheritance with CreateView, FormMixin and ModelFormMixin and I got all of them to work, but when a form is invalid, I don't get validation, I just get 'View' object has no attribute 'object_list'. How can I achieve that? Should I split my concerns and have a separate view just to handle Model creation? If so, how can I get the invalid errors back to the same template? My code atm: @method_decorator(login_required, name='dispatch') class MyView(CreateView, ListView): model = MyModel form_class = MyModelForm template_name = 'MyPage.html' success_url = reverse_lazy('my_page') -
configure React (build) routes.js with Django urls.py
I created a web application: backend with Django & frontend with React in Django I have some views I want to ignore, and let React routes.js handle the urls in React I have file routes.js I would like to include After npm run build I integrated the build folder into my Django project. I'm able to get to index.js in React build folder - but the url paths from react routes are not working. How I can integrate the routes from my routes.js file into the urls? /clients will take me to the Django view, and /control isn't available url Project Map React (original project) > routes.js ... const BaseRouter = () => ( <div> <Route exact path='/control' component={Control} /> <Route exact path='/suppliers' component={Supplier} /> <Route exact path='/clients' component={ClientsList} /> ... Django > urls.py ... from django.views.generic import TemplateView app_name = 'inventory' urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), path('clients/', views.filter_clients, name='filter_clients'), ... -
Heroku could not connect to server: Connection refused
Made a website design through a tutorial, on django and boostrap. It all works fine on my django local server, but when I try to deploy it, something goes wrong. Getting this error when I try to open my app through their website. I did a pip3 freeze and updated the requirements.txt.\ The Error I get. OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Request Method: GET Request URL: https://chrisleeslacker-website.herokuapp.com/ Django Version: 3.0.8 Exception Type: OperationalError Exception Value: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Exception Location: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py in connect, line 127 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.11 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Fri, 31 Jul 2020 23:31:35 +0000 The Requirements.txt absl-py==0.9.0 appdirs==1.4.4 asgiref==3.2.10 astunparse==1.6.3 blis==0.4.1 cachetools==4.1.1 certifi==2020.6.20 chardet==3.0.4 cloudpickle==1.5.0 comtypes==1.1.7 distlib==0.3.1 Django==3.0.8 filelock==3.0.12 fpdf==1.7.2 future==0.18.2 gast==0.3.3 google-auth==1.20.0 google-auth-oauthlib==0.4.1 google-pasta==0.2.0 grpcio==1.30.0 gunicorn==20.0.4 gym==0.17.2 gym-super-mario-bros==7.3.2 h5py==2.10.0 idna==2.10 imageio==2.9.0 Markdown==3.2.2 nes-py==8.1.4 numpy==1.19.1 oauthlib==3.1.0 opencv-python==4.3.0.36 opt-einsum==3.3.0 pandas==1.1.0 Pillow==7.2.0 protobuf==3.12.4 psycopg2==2.8.5 psycopg2-binary==2.8.5 pyasn1==0.4.8 pyasn1-modules==0.2.8 pyglet==1.5.7 python-dateutil==2.8.1 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 requests-oauthlib==1.3.0 rsa==4.6 scipy==1.5.2 six==1.15.0 sqlparse==0.3.1 termcolor==1.1.0 urllib3==1.25.10 virtualenv==20.0.29 … -
how can i solve The view blog.views.post_detail didn't return an HttpResponse object. It returned None instead
''' def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post,status='published', publish__year = year, publish__month = month, publish__day = day ) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() # context = {'post':post,'comments':comments,'new_comment':new_comment, 'comment_form': comment_form ,} # return HttpResponse(template.render(context, request)) return render (request, 'blog/post/detail.html', {'post':post,'comments':comments,'new_comment':new_comment, 'comment_form': comment_form ,}) ''' -
How can I generate a random value for username in django user model?
I am satisfied with django default user model but I want the user name to be autogenerated. I don't want to create a custom user model. I need to define a function that generate unique random usernames as follows : user = User.objects.create_user(username=generate_username()) def generate_username(): pass I don't want to generate a random username using random module and then check if it exists, otherwise, create another random, check it again and so on. Is there a fast way to do this ? -
Django : How to pass custom value to inline css
I am writing to pass custom values to the inline css , but i am unable to get this since i am very new to django framework . Thanks in Advance <div class="progress-bar bg-success" role="progressbar" style="width: {{news_curr_idx}}" aria-valuenow="25" arwiria-valuemin="0" aria-valuemax="100">{{news_curr_idx}}</div> </div> -
Gunicorn Supervisor not reflecting new code
On django, I made some changes, and supervisor is not reflecting new code. I tried to kill gunicorn. Kill supervisor, supervisorctl restart all, reboot server. None of this seems to work. If I just run server as manage.py, new code is being reflected. What else needs to be done so that supervisor is reflecting new code? -
How to localize numbers only?
I have a Django app with all texts and controls in English, but I need to show numbers in the correct local format; i.e. using appropriate symbols for decimal points and thousands separation. Everything else, including dates, I would like to keep in English format. With USE_L10N=True and USE_I18N=True, all numbers and dates get formatted according to the language set in HTTP headers. With USE_L10N=True and USE_I18N=False, only numbers get formatted, but the language set in HTTP headers is ignored; i.e. the numbers are formatted according to settings.LANGUAGE_CODE. This seems to be by design: django/blob/master/django/utils/translation/trans_null.py I must be missing something. What is the best practice for localising numbers only? Thank you. -
TypeError: 'class Meta' got invalid attribute(s): get_absolute_url
I've been unable to troubleshoot this problem from other questions posted. I've been following a bookstore on a Django tutorial. Below is my models.py code. import uuid from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class Book(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) cover = models.ImageField(upload_to='covers/', blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', kwargs={'pk': str(self.pk)}) class Meta: permissions = [ ('special_status', 'Can read all books'), ] def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) class Review(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='reviews', ) review = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.review I have tried using "Modelform" instead of "Model" but to no avail. -
Style Guidelines in Django
I am new to Django and am using it to build a dashboard (backend and frontend). I want to know what the best style practices are and was wondering if anyone could link some repositories that have good Django style. Thanks! -
How do I scrape and use OpenGraph (og) tags to create rich previews?
I am a beginner and I am creating a blog-like website with Django. I would like to be able to create rich previews of links, so when a user sends a post with a link, it gets displayed in the forum as a clickable rich-preview (an image, title and description), just like Twitter and FB does. Here is an example (look at the Medium link and the 'The Reason' Youtube link). To do this I think I need to create the site so that it automatically scrapes the source code of the link for its og or twitter tags, and extracts the necessary data. For example the title, description and image in this: <meta property="og:title" content="How to Become an SEO Expert (8 Steps)" /> <meta property="og:description" content="Get from SEO newbie to SEO pro in 8 simple steps." /> <meta property="og:image" content="https://ahrefs.com/blog/wp-content/uploads/2019/12/fb-how-to-become-an-seo-expert.png" /> I do not know where to start so please can someone help me understand how to do this? Which tools do I need to use and what is the best way to use them to achieve my goal? I would like to have as much control as possible (and use as few 3rd-party tools as possible). -
ImageField not loaded via HTTPS with nginx reverse proxy and docker
I have the following setup: I'm using nginx reverse proxy, to distribute incoming requests to different docker instances which all have Django running as an API. If I make HTTPS-Requests, everything is working fine, but for images it's not. Even if I set proxy_set_header X-Forwarded-Proto $scheme; and SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') in the reverse proxy nginx and the docker nginx, Django still returns images from ImageField as HTTP. The browser marks my Website as not secure, because the images are requested via HTTP and then redirected to HTTPS (which is working). What do I have to do, to get the images from Django as HTTPS? -
django Choice list (dynamic choices)
i have a choices list : CATEGORY_CHOICES = ( ("T-shirts", "T-shirts"), ("Hoodies", "Hoodies"), ("Shorts", "Shorts"), ) but i want to make this list dynamic so i can add and delete choices ,i created a new model Category what i want to do is something like this : CATEGORY_CHOICES = ( for choice in Category.object.all(): (choice.category, "choice.category"), ) but it doesn't seems to work -
how do update a model after the return statement
I have a view when should update the model data as "Sent" after rendering to template. I want to exclude things that are already sent then update the value no (number) as sent then return the data to the template. the problem is that if i use it as it is it seem to do all three liunes in one go and excludes the no as its been sent,, how can I update it as sent AFTER the data is returned. def get(self, request, *args, **kwargs): lab = request.GET.get('lab', None) audit = models.SendAudit.objects.filter(no__exact=labno).exclude(status__contains='sent') models.SendAudit.objects.select_related().filter(no__exact=labno).update(status='{Sent}') return render(request, self.template_name2, {'audit': audit, 'no': no}) -
How do I handle a category object in django models and forms?
I have a model for, let's say, Items. These can be any sort of physical items, and they're created using a form via a POST request. During that creation, I want to attach one of a limited number of category choices to each item. There can only be one category per item. Thus I believe each Item should have a foreignkey to a Category (many-to-one relationship). That seems simple enough. But when I try to implement it via the two models and a ModelForm, the category choices don't display. I'm thinking that I don't actually have any Category instances in the database, and thus can't grab them to associate with the Items. Should I check for a given category's existence when I process the POST, then create it if necessary, then associate it with the Item? Or would it be better to manually create the Category instances in the database? Here's what I have in .models (I'm paring everything down for simplicity's sake): class Item(models.Model): name = models.CharField(max_length=150) category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name="items") class Category(models.Model): PERSON = 'PE' PLACE = 'PL' THING = 'TH' CATEGORY_CHOICES = [ (PERSON, 'Person'), (PLACE, 'Place'), (THING, 'Thing'), ] name = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default=PERSON) Here's … -
error 404, javascript http request goes to /favicon.ico in django server
in views.py: def recommend(request): return HttpResponse('hello') i have this simple HttpResponse that is at the route /recommend. When i go to this route with the browser, i can see it's working, but when i try to get this http response with javascript: <script> ///request to /recommend route function recommend(){ const req = new XMLHttpRequest() req.open('GET','/recommend') req.onload = () =>{ console.log(req.response) } } window.onload = ()=>{ recommend() } </script> I get the error 404 in the browser console, and django says me that: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/favicon.ico Using the URLconf defined in V_store.urls, Django tried these URL patterns, in this order: recommend The current path, favicon.ico, didn't match any of these.] How can i get this response with javascript? Why the request is going to /favicon.ico -
Django : How create an TextField on dropdown select
Can someone help me out , i am trying to create a text box based on selecting a dropdown option. If a user selects a particular dropdown option i want to create a text box. Thanks in advance View.py def report_issue(request): news_curr_idx = request.user.profile.news_curr_idx news_curr = NewsItem.objects.all().filter( chunk_id=request.user.profile.assigned_chunk_idx)[news_curr_idx] context = { 'news_curr_idx': news_curr_idx + 1, } if request.method == 'POST': issue_form = IssueForm( request.POST, newsItem=news_curr, author=request.user.profile) if request.POST.get("action_name") == 'CANCEL': assert not IssueReport.objects.filter( author=request.user.profile).filter(newsItem=news_curr).values() return redirect('question') if issue_form.is_valid(): issue_form.save() request.user.profile.news_curr_idx += 1 request.user.profile.save() assert IssueReport.objects.filter( author=request.user.profile).filter(newsItem=news_curr).values() return redirect('question') else: # TODO add logger print(issue_form.errors.as_json()) return render(request, 'annotating/issue_reporting.html', context) forms.py class IssueForm(forms.ModelForm): class Meta: model = IssueReport fields = ('issue_type', 'issue_comment') def __init__(self, *args, **kwargs): self.newsItem = kwargs.pop('newsItem') self.author = kwargs.pop('author') super().__init__(*args, **kwargs) def save(self): issue_report = super().save(commit=False) issue_report.newsItem = self.newsItem issue_report.author = self.author issue_report.save() return issue_report