Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get XML data from a requests.post in Django
I'm sending a request like this in Django: response = requests.post('https://ws.sandbox.pagseguro.uol.com.br/v2/transactions', headers=headers, params=params, data=data_ps) When I print(response.text) I got the following answer: <?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> <transaction> <date>2020-08-22T14:57:23.000-03:00</date> <code>CCBA67EC-D4C8-42F2-BC84-15C910A36B84</code> </transaction> How can I get the code number (CCBA67EC-D4C8-42F2-BC84-15C910A36B84)? Thank you! -
Unresolved library error when trying to load custom tag in Wagtail CMS
I am new to Wagtail but have some knowledge in Django. I was trying to follow the official documentation of Wagtail but I got stuck in the snippets section. I am trying to render a snippet NavigationComponent in home/templates/home/home_page.html. I have defined a tag in home\templatetags\navigation_tags.py to render it. However when I am trying to load the tag using {% load %}, it doesn't recognize it. Here is the code:- [base.py] INSTALLED_APPS = [ 'home', 'search', 'website', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ########################################################################################### [home/models.py] from django.db import models from wagtail.core.models import Page from wagtail.snippets.models import register_snippet from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel class HomePage(Page): pass @register_snippet class NavigationComponent(models.Model): name = models.CharField(max_length=50, blank=False) link = models.ForeignKey( 'wagtailcore.Page', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) url = models.URLField(blank=True, null=True) panels = [ FieldPanel('name'), PageChooserPanel('link'), FieldPanel('url') ] def __str__(self): return self.name class Meta: verbose_name_plural = 'Navigation Item Container' verbose_name = "Navigation Item Container" @register_snippet class NavigationItem(models.Model): name = models.CharField(max_length=50, blank=False) link = models.URLField() class Meta: verbose_name_plural = 'Navigation Items' [home/templatetags/navigation_tags.py] from django import template from ..models import NavigationComponent register = template.Library() @register.inclusion_tag('../templates/tags/navigation_component.html', takes_context=True) def navigation_components(context): return { 'components': NavigationComponent.objects.all(), 'request': context['request'] … -
How to check password against previously used passwords in django
I have the following model for storing previously used hashed passwords: class PasswordHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) password = models.CharField(max_length=128, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) In the change password form I want check if the new password the user is changing to has not been used the past 5 times. Here is my form validation: class ProfileForm(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), required=False) password2 = forms.CharField(widget=forms.PasswordInput(), required=False) class Meta: model = Employee user_id = None def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id', None) super(ProfileForm, self).__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise forms.ValidationError('Passwords do not match.') user = User.objects.get(pk=self.user_id) hashed_password = user.set_password(password1) print(hashed_password) password_histories = PasswordHistory.objects.filter(user=user) for ph in password_histories: print(ph.password) if hashed_password == ph.password: raise forms.ValidationError('That password has already been used') return password2 The problem is that this line returns None: hashed_password = user.set_password(password1) It also saves the password to the user which the document says it does not do here: https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.set_password How can I compare a proposed new password against previously used passwords? Thanks -
The proper way to set user ForeignKey value in DjangoRestFramework
I have this model: class Comment(models.Model): user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) def __str__(self): """Return the comment str.""" return "'{}'".format(self.content) And its serializer looks like this: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' So far so good when it comes to retrieve data, but when I want to create a new Comment, what would be the proper way to do so? My view: class CommentViewSet(viewsets.ModelViewSet): def get_permissions(self): permissions = [] if self.action == 'create': permissions.append(IsAuthenticated) return [p() for p in permissions] def create(self, request): """Create a comment in some post.""" serializer = CommentSerializer(data=request.data) if serializer.is_valid(): # False because user value is missing. serializer.save() return Response(serializer.data) else: return Response(serializer.errors) That's ok, I tried by overriding validate_user and letting it just pass, but validation is still running when I call is_valid. Also I tried to append request.user to serializer.data, but it's immutable. How could I achieve this if I need to use request.user? The value that I need to set to this field of the serializer is not in request.data. (I don't think letting the front end send the user id would be a good idea). Another solution I have … -
how to structure django templates with django restframework
I have a Django project that currently has the following structures: And each sub-packges (marketdata / oms / portfolio / rebalance) are all django apps that just provide Restful APIs, and they all get mapped in the "app\url.py" like this: I am trying to build the front-end of the project using Django template engine. Where do you think I should put my template files to? Should I create a new app within this project called "front-end" and put them all there? or should I put them under the most relevant existing apps (for example, login.html goes into "user" app) Thanks guys -
How to host multiple django rest framework apps in apache virtual hosts for windows
Here is the config of vhost file in apache windows. It is working but everytime the request is going to the same app which is first in WSGIPythonPath variable. i.e., the two url request will directs to 'company1'. Listen 192.168.168.202:7089 Listen 192.168.168.202:7099 WSGIPythonPath "C:/ApacheDevServer/htdocs/company1/Django_WebServices;C:/ApacheDevServer/htdocs/company2/Django_WebServices" <VirtualHost 192.168.168.202:7099> ServerName 192.168.168.202 WSGIScriptAlias / C:/ApacheDevServer/htdocs/company1/Django_WebServices/Django_WebServices/wsgi.py WSGIPassAuthorization On <Directory C:/ApacheDevServer/htdocs/company1/Django_WebServices> Allow from all Require all granted </Directory> </VirtualHost> <VirtualHost 192.168.168.202:7089> ServerName 192.168.168.202 WSGIScriptAlias / C:/ApacheDevServer/htdocs/company2/Django_WebServices/Django_WebServices/wsgi.py WSGIPassAuthorization On <Directory C:/ApacheDevServer/htdocs/company2/Django_WebServices> Allow from all Require all granted </Directory> </VirtualHost> Can anybody help. Thanks in advance. I want it to work in windows only. -
How can include a regular Django view content in a Wagtail page?
I have a website running on Django that uses Wagtail for most of the pages (that are simply text content, editable through the Wagtail Admin UI). However, I have some content that needs to be dynamically rendered from my own Django model (let's say it's a list of handouts). I'd like that content to be rendered on a Wagtail page that would also have some Wagtail models (e.g., top menu, some introductory text). What's the best way to do this? I thought about making the list of handouts an API endpoint, and rendering it with JavaScript + XHR, but it seems like there should be a good way to do it server-side. -
Follow & unfollow system django
i have follow and unfollow system for my app but when i want that using the if statement html changes from follow to unfollow automatically.. but unfortunately my for loop always gives False in views.py and i don't know what is wrong. here is my models.py file class FollowUser(models.Model): profile = models.ForeignKey(to=Profile, on_delete=models.CASCADE) Followed_by = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self): return "%s" % self.Followed_by here is my views.py file class UserListView(ListView): model = Profile context_object_name = 'users' template_name = 'dashboard/user_list.html' def get_queryset(self): si = self.request.GET.get("si") if si == None: si = "" profList = Profile.objects.filter(Q(phone__icontains = si) | Q(location__icontains = si) | Q(gender__icontains = si) | Q(organization_name__icontains = si)).order_by("-id"); for p1 in profList: p1.followed = False ob = FollowUser.objects.filter(profile=p1, Followed_by=self.request.user.profile.id) if ob: p1.followed = True return profList -
How to get top5 users by the quantity (2 tables connected with each other)?
My models: class Institution(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) type = models.CharField(choices=type_of_organization, default=1, max_length=32) categories = models.ManyToManyField(Category) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) class Donation(models.Model): quantity = models.IntegerField() institution = models.ForeignKey(Institution, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) How can i get top 5 users by the quantity for each Institution? For example, for Institution_id = 1? -
AUTH_PASSWORD_VALIDATORS = [ <== SyntaxError: invalid syntax
I deployed my local repo to heroku and when I tried "heroku run python manage.py migrate" the error AUTH_PASSWORD_VALIDATORS = [ ^ SyntaxError: invalid syntax comes out. I checked the syntax if there's any missing things but I couldn't find any. What should I do to fix this? Below is my full error log File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/init.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 83, in getattr self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/init.py", line 177, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 724, in exec_module File "", line 860, in get_code File "", line 791, in source_to_code File "", line 219, in _call_with_frames_removed File "/app/config/settings.py", line 127 AUTH_PASSWORD_VALIDATORS = [ ^ SyntaxError: invalid syntax -
Saving different styling formats in Django
I'm trying to build a blog site with Django and I'm wondering how it's possible to save different styling for different posts when creating a post. Something like the editor when creating a question here in Stackoverflow. If lets say the post has highlighted text or code snippet or quotes. How do I save the different styles for different posts? -
Many to Many relationship query returns empty queryset on post_save signal but not in django shell
I have a function in my model that send an email on successful save. But i am struggling to figure out why print statement on signal function in the model returns empty queryset but not in the shell. Below is my code. Model code class Booking(models.Model): """Database table for users booking details""" //more code here items = models.ManyToManyField(BookingItems) //more code here def send_confirmation_email(sender, instance, **kwargs): """Function to send email upon successfull booking creation""" name = instance.guest_name total = instance.final_total, email = instance.email order_number = instance.reservation_id bookingId = instance.id itemsData = instance.items.all() booking = Booking.objects.get(id=bookingId) bookingItems = booking.items.all() print(bookingItems)-----------------------------------> this returns empty queryset <QuerySet []> context = {"name": name, "items": itemsData, 'total': total, 'order_number': order_number} message = render_to_string( "reservations/room_reservation_success.html", context) plain_message = strip_tags(message) subject = f"Your booking details for {instance.hotel.name}" mail.send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [ email], html_message=message) post_save.connect(send_confirmation_email, sender=Booking) Code from shell >>> book = Booking.objects.filter(id=61) >>> print(book[0].items.all()) <QuerySet [<BookingItems: One bedroom>, <BookingItems: Two bedroom>]> >>> What could be the issue here. Why is it returning empty set when there's clearly related child items? Kindly assist -
Django order_by causes query to be very slow
I have a model Line with a total_value and a group fields. I use the following code to get the 10 lines with the highest values within a given group: group_lines = Line.objects.filter(group_id=group_pk, total_value__gt=0) sorted_lines = group_lines.order_by('-total_value')[:10] ids = lines.values_list("id", flat=True) My database is very large, with 10M+ lines. The group_lines query alone returns 1000 lines. My issue is that the values_list query takes about 2 seconds to get executed. If I remove the ordering, it is almost instant. Is it normal to take that long to order 1000 objects? How can I make this query faster? I am on Django 2.1.7, with a MySQL database. -
Calculate streak by date in django
I'm developing a habit tracker using django. The models of the project are the following: class Habit(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField(max_length=500) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.user.username + " - " + self.title class HabitRecord(models.Model): COMPLETION_CHOICES = ((0, "NOT DONE"), (1, "COMPLETED")) habit = models.ForeignKey(Habit, on_delete=models.CASCADE) note = models.TextField(max_length=500, default="") fire_date = models.DateField(auto_now_add=True) completion_status = models.IntegerField(choices=COMPLETION_CHOICES, default=1) def __str__(self): return str(self.fire_date) now I need to calculate the current streak of a habit (how long a habit has been marked as COMPLETED in a row). Therefore a method called get_streak should be implemented. What is the best way to implement this? -
How can I autofill a field in my django form?
I am trying to create a very simple form for users to borrow book from a library and I have a button to borrow book that redirects user to another page. Once the user is redirected all i want to allow him is to click submit or cancel for specific book. My model for that: class Borrowed(models.Model): person = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL) book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL) taken_date= models.DateField(auto_now_add=True) return_date= models.DateField(default=datetime.today()+timedelta(days=90)) def __str__(self): return f"{self.person} borrowed {self.book}" views.py: def borrow(request, pk): book = Book.objects.get(id=pk) if request.method == 'POST': # form = BorrowForm(instance=request.user.person) form = BorrowForm(request.POST, initial={Book: book.title}) if form.is_valid(): form = form.save(commit=False) form.person = request.user.person form.book = book.title form.save() return redirect('all_books') else: form = BorrowForm(initial=book.title) context = {'form': form, 'book': book} return render(request, 'rental/borrow.html', context) forms.py class BorrowForm(forms.ModelForm): class Meta: model = Borrowed fields= ['book'] I don't know how and where exactly to do that because I am new to Django. Help would be appreciated. Thank you -
Set-Cookie is not working in Chrome and Dolphin - with two websites
Please see this question and answer from 8 months ago. The answer fixed the problem for a while, but today I discovered that login and logout works again separately for each of my websites (domains), in Chrome and in Dolphin. But, everything works as before in Firefox, Edge and Opera. Did something change in those browsers regarding cookies from other domain names and how do I fix it so that login and logout will work simultaneously in both websites? The users login or logout or sign up to one website, and I want them to login or logout from the other website too, automatically, and it works with Firefox, Edge and Opera. Currently if they login or logout to one website, it doesn't affect the other website (with Chrome or Dolphin). The Django view code is: @csrf_exempt def set_session(request): """ Cross-domain authentication. """ response = HttpResponse('') origin = request.META.get('HTTP_ORIGIN') if isinstance(origin, bytes): origin = origin.decode() netloc = urlparse(origin).netloc if isinstance(netloc, bytes): netloc = netloc.decode() valid_origin = any(netloc.endswith('.' + site.domain) for site in Site.objects.all().order_by("pk")) if (not (valid_origin)): return response if (request.method == 'POST'): session_key = request.POST.get('key') SessionStore = import_module(django_settings.SESSION_ENGINE).SessionStore if ((session_key) and (SessionStore().exists(session_key))): # Set session cookie request.session = SessionStore(session_key) request.session.modified … -
TypeError: Cannot read property 'file' of undefined, while updating Django model
I update my model with axios and file field causes some error. I use PATCH method for updating and this means i can include only one field to change. For example when i only post new picture, my image field will be updated and i can leave other fields empty. So updating only my image fields works. But now when i try to update only my name field, next error occurs. TypeError: Cannot read property 'file' of undefined And next thing is that when i update my image field and name field at the same time, this also works and my model gets updated. This is really confusing error but i hope someone knows what could cause issue here. Thanks in advance! My form handling method: handleFormSubmit = (event) => { event.preventDefault(); let form_data = new FormData(); form_data.append('name', event.target.elements.name.value); form_data.append('email', event.target.elements.email.value); form_data.append('location', event.target.elements.location.value); form_data.append('sport', this.state.sport); form_data.append('image', this.state.file.file, this.state.file.file.name); console.log(form_data.image); const profileID = this.props.token let url = `http://127.0.0.1:8000/api/profile/${profileID}/update` axios.patch(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => console.log(res)) .catch(error => console.err(error)); } In the frontend i also use ReactJS and for Form, Ant Design Form, but it shouldn't matter -
POSTGRESQL and Django app: could not receive data from client: Connection reset by peer
I am running a django app with postgresql, nginx and gunicorn. I have a script where data is pulled from one table in the DB, modified and then needs to replace the existing data in that one table. In the same script, a few tables are also being updated. When runnning the script, it always results in 502 Bad Gateway because the server times out because of something in the script. Being fairly new the topic, I am struggling to figure out what is going on with the following error. I only have the following log to work with from postgres: 2020-08-22 14:57:59 UTC::@:[8228]:LOG: checkpoint starting: time 2020-08-22 14:57:59 UTC::@:[8228]:LOG: checkpoint complete: wrote 1 buffers (0.0%); 0 WAL file(s) added, 0 removed, 1 recycled; write=0.101 s, sync=0.005 s, total=0.132 s; sync files=1, longest=0.005 s, average=0.005 s; distance=65536 kB, estimate=70182 kB 2020-08-22 14:58:50 UTC:address-ip(45726):pierre@dbexostock:[25618]:LOG: could not receive data from client: Connection reset by peer 2020-08-22 14:58:50 UTC:address-ip(45724):pierre@dbexostock:[25617]:LOG: could not receive data from client: Connection reset by peer I think the issue is inside of the connections to the database in the script: #connect to db engine = create_engine('postgresql+psycopg2://user:password@amazon.host.west', connect_args={'options': '-csearch_path={}'.format(dbschema)}) #access the data in the historical_data table conn = engine.connect() metadata … -
django how to use filter for ForeignKey
Hi thank you for watching. My question is how do I filtering for category category [fruits, vegetable] post [apple, banana, onion] For example, If I click fruits show apple, banana python 3 / django 3 project/app/models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.PROTECT) category category1 name=fruits category2 name=vegetable post post1 title=apple category=fruits post2 title=banana category=fruits post3 title=onion category=vegetable python manage.py shell >>> from post.models import * >>> category = Category.objects.all() >>> print(category) <QuerySet [<Category: vegetable>, <Category: fruits>]> >>> post = Post.objects.all() >>> print(post) <QuerySet [<Post: apple>, <Post: banana>, <Post: onion>]> thank you for reading until end. -
Using login view provided by django instead of custom login view
I am working on a django website. I have my own custom user model. and this is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) return redirect('/category/all') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") I wanted to shift to the login_view provided by django to get features such as next after login which does not happen with my custom view. So in my urls can I just use login view or do i have to make some changes in my templates and user model or is it not possible to shift to pre provided login view after having a custom user model. -
How to nest up to 5 models in Django Admin page?
I have a book object which needs to be categorized up to sub 5 categories. The business requirement required the admin to add these categories page by page by first adding first-level categories and then click on each on to add second-level categories, After that, click on each one to add the third-level and so on up to 5. the below figure can describe the idea. Django inlines can add two objects of different models on the same page Which can help me only for the second-level categories, but what if I want to click in that second object to add subs inside it? Is that possible in Django? from the DB side, I think one table with the following attributes: key, value, and parent can help me in storing all the categories and whenever I wanted them on the client side I can arrange them before sending them in views. But the issue is on the admin side, how can I do it in that way? Thank you. -
Django Polling App gives an error of "No Polls are Available"
I did a search on all past answers but unable to get a clue. In the Django Polling App tutorial, I have reached generic views. After defining views.py, urls.py and the templates (index.html, detail.htmls and results.html) when i go to the url localhost:8000/polls/ I get the message no polls are available. If I go to the url localhost:8000/polls/1/ I can see the "What's New?" question with choices. My files below : views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Question, Choice from django.urls import reverse from django.views import generic from django.utils import timezone # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now().date()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', {'question': question, 'error_message': "You didn't select a choice.",}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) urls.py from django.urls import path from . import views app_name = … -
I'm trying to run the package, pip install psycopg2==2.7.* ,on my pycharm terminal so I can deploy my site but i get the message that appears
Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/a8/8f/1c5690eebf148d1d1554fc00ccf9101e134636553dbb75bdfef4f85d7647/psycopg2-2.8.5.tar.gz ERROR: Command errored out with exit status 1: command: /Users/applecare/PycharmProjects/learning_log/11_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /private/var/folders/w6/sqx_mjh176x08sjppl82f1l80000gn/T/pip-install-8j8wbzsu/psycopg2/ Complete output (23 lines): running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.2.3, however version 20.2.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. -
Django ignore 500 errors
I have developed an ecommerce store in Django where I am using twilio sms functionality. Using twilio, sms only sends if number is in proper format and valid. message = client.messages.create( body="Dear costumer, this is sample msg", to= number, from_= contact ) So I want a way through which if twilio raise an error in sending sms, this errors gets ignore [Don't raise Server Error 500 in prod]. And Website functionality remains normal. Is there any way to cater it? -
Static files doesn't update - Django
This is the second time i'm commenting about this problem and I really hope you can help me this time since i've gained some more information about the problem. So the problem is basically that all my Django projects doesn't update the static files (this also includes projects which I have downloaded). So I can fx still see the old styling from the css files but the changes is not displayed. When i insert the css or js directly into the html file i can see it though. I thought that it maybe had something to do with my browsers stored caches but I have tried to do a hard refresh, clearing all my caches, installing whitenoise and forced browser to reload the css file by adding an extra parameter to the end of the src tag. I have also tried python manage.py collectstatic and almost everything else on this thread. When the problem bagan to occur I was working with the implementation of stripe. I don't neccessarily think that stripe is the problem since the problem occured hours after i had already implementet the checkout site. I just think it's worth at least mentioning. Some of my venv packages: …