Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: 'WSGIRequest' object has no attribute 'Post'
Im kinda new to Django and already stuck at some simple POST-problem. Heres the HTML within profile.html: <form action="{% url 'profile' %}" method="post"> {% csrf_token %} <input type="text" placeholder="Weight", name="weight"> <input type="text" placeholder="Reps", name="reps"> <input type="submit"> </form> And heres the correspoding view: def profile(request): if request.method == "GET": return render(request, "userprofile/profile.html") elif request.method == "POST": print(request.Post) return render(request, "userprofile/profile.html") Basically, all I want to do for now, is to print the POST-data dictionary into the Terminal. However, I get the following error: AttributeError at /profile/ 'WSGIRequest' object has no attribute 'Post'. What am I missing? Thanks so much for any help! -
How do I fix no module found error in Django?
I'm reading the Django docs and I'm going through the first project called "mysite" and it has an app called polls This is my file structure : \pythonproject \mysite \mysite \polls \migrations __init.py__ admin.py apps.py models.py tests.py urls.py views.py __init__.py db.sqlite3 manage.py I am in this location : polls\urls.py and I want to import "polls\views.py" So I type in this : from mysite.polls import views And I get the error when I ran: python manage.py test This is the error : No module found "mysite.polls" The error refers to the second line of code in polls\urls.py I am using pycharm and my Django version is "3.2.8" My python version is "3.10" -
why is the form works in "is_valid" but doesn't update objects?
I'm trying to update this field, when I do "forms.is_valid" and print anything into it like print("updated") as you can see below, this print works fine which means that "is_valid()" produce a "True" value, however, nothing is updated in a database then. anyone can help please: views.py def review_membership(request, id=None): roles = str(User.objects.get(email=request.user).roles.get()) membership = MemberShip.objects.get(id=id) user_admin = User.objects.get(roles__id='Admin') forms = MemberShipForm() disable_field = True if request.user.email == membership.ambassador.email: disable_field = False if membership.status == "Pending": if roles == "SubAmbassador": if restrict_see_report(request) == True: field_disabled(forms) if request.method == "POST": if "update" in request.POST: forms = MemberShipForm(request.POST) # print(User.objects.get(email=membership.ambassador)) if forms.is_valid(): forms.instance = request.user print('updated') forms.save() messages.success(request, 'This field has updated') return redirect('index:review_membership', membership.id) forms.py class MemberShipForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control'})) price = forms.IntegerField(widget=forms.NumberInput(attrs={'value': 0, 'class': 'form-control'})) description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'type a description here...', 'class': 'form-control'})) class Meta: model = MemberShip fields = ['name', 'price', 'description'] models.py class MemberShip(models.Model): name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=False, null=True) price = models.PositiveIntegerField(default=0) ambassador = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sub_ambassador = models.ForeignKey(SubAmbassador, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=20, choices=MEMBERSHIP_STATUS, default='Inactive') def __str__(self): return self.ambassador.email def get_status(self): return self.status -
django-rest-framework-social-oauth2: error 400 - redirect_uri_mismatch
I've been trying to add google login to my django app following this tutorial: https://github.com/RealmTeam/django-rest-framework-social-oauth2 By following exactly the instructions, everything works fine in local. However, when I try to replicate the same on the server, I get the following error on the redirect page of the login: Error 400: redirect_uri_mismatch redirect_uri: http://localhost:8000/auth/complete/google-oauth2/ What is strange to me is, in my google developer console, I have set up the correct redirect url in my app, as follows: https://mydjangoapp.com/auth/complete/google-oauth2/ And I have also put 'mydjangoapp.com' under 'Authorised JavaScript origins'. So my question is, why google keeps telling me that the redirect url is http://localhost:8000/auth/complete/google-oauth2/ which is not the one I have set up in the console? Perhaps there is something obvious that I'm missing here. Thank you! -
Charts not being displayed in django app when using Chart.js 3.6 version
I have a Django application which has charts. They were implement in Chart.js 2.9 version. When I upgraded to Chart.js 3.6 version, I am unable to view the charts. I have check those charts in a standalone HTML page. They work fine there. -
Error 32 when Twitter sign in with Django AllAuth and post tweet with Tweepy
I'm using Django AllAuth for twitter login, and it's working perfectly and saving the token and token secret to the Social Account Tokens table. I'm then trying to use Tweepy to send a tweet on the user's behalf (yes, the scope allows that). But when I try to send the tweet, I get tweepy.error.TweepError: [{'code': 32, 'message': 'Could not authenticate you.'}] Here's the auth code: def auth_tweepy(user): twitter_auth_keys = settings.TWITTER_AUTH_KEYS auth = tweepy.OAuthHandler( twitter_auth_keys['consumer_key'], twitter_auth_keys['consumer_secret'] ) user_auth = SocialToken.objects.get(account__user=user, account__provider='twitter') auth.set_access_token( user_auth.token, user_auth.token_secret ) return tweepy.API(auth) def send_tweet(tweet_content): api = auth_tweepy(user) try: api.update_status(tweet_content) except tweepy.TweepError as error: if error.api_code == 187: print('duplicate message') I dont think the tokens are expired bc I JUST logged in. Any ideas what might cause the 32 error in this case? -
How django + restframework implements the parameter interface through inherited classes
When my RegisterView inherits APIView and cannot display parameters, what should I do to make RegisterView display parameters like LoginViewHow to make register display interface parameters like login. -
Error when connecting to a scss file in django
I am trying to connect to my scss file in static, but I get the following error: sequence item 1: expected str instance, WindowsPath found The error supposedly comes from the following line of code in my base.html: <link href="{% sass_src "css/main.scss" %}" rel="stylesheet" type="text/css" /> When I looked up in the Internet, I read that some say it is a specific error that happens for people using a windows os. Do you guys know why this error is happening, and how to solve this issue so that I could use my scss file for the templates? Please ask me any questions. -
How can I get latest record by queryset. like group by
Data name data1 data2 create_date iron man ia ib 1630000000 hulk ha hb 1630000000 hulk hc hd 1630500000 captain ca cb 1630000000 captain cc cd 1630500000 captain ce cf 1630590000 I want to get latest data each name name data1 data2 create_date iron man ia ib 1630000000 hulk hc hd 1630500000 captain ce cf 1630590000 like this wish_data = [ {'name':'iron man', 'data1': 'ia', 'data2': 'ib', 'create_date':1630000000}, {'name':'hulk', 'data1': 'hc', 'data2': 'hd', 'create_date':1630500000}, {'name':'captain', 'data1': 'ce', 'data2': 'cf', 'create_date':1630590000}, ] I tried... Model.objects.filter(**conditions).values_list('name').annotate(cdate=Max('create_date')) => [('iron man', 1630000000), ('hulk', 1630500000), ('captain', 1630590000)]> but i need to other columns... Q Is it possible with ORM? Or do I have to write the logic with for and if statements? -
How to change Django admin url for rewrite urls
I have Django project, which is deployed to kubernetes, where I need to rewrite the admin url to different endpoint. Currently my admin endpoint is mapped as below: url(r'^admin/', admin.site.urls) Which works fine in local and ingress url when I try to access my it using <BASE_URL>/admin. But now I have to rewrite my service url to different endpoint in Kubernetes for example as below: spec: prefix: /app/sevice/admin/ rewrite: /admin/ After this I'm able to access my admin panel home page with ambassador url <AMBASSODER_BASE_URL>/app/service/admin only when I'm already logged-In to admin and after I click on any of the table listed in admin UI it throws me to <AMBASSODER_BASE_URL>/admin> because I can still see admin UI html href /admin/../... Is there any way to make those href to use relative path rather then full path. I mean just the path after /admin. -
Search Bar Problems showing email
My search bar showing me to give it a email address or it will not accept it. Thanks in advance. for email bar def index(request): if request.method =='GET': email = request.GET.get('email') if email: subscribe(email=email).save() views.py def search(request): q = request.GET.get('q') posts = Post.objects.filter( Q(title__icontains = q) | Q(overview__icontains = q) ).distinct() parms = { 'posts':posts, 'title': f'Search Results for {q}', 'pop_post': Post.objects.order_by('-read')[:9] } return render(request, 'all.html', parms)` base.html : -
Django: How to do full-text search for Japanese (multibyte strings) in Postgresql
It is possible to create an index for searching using SearchVector, but However, Japanese words are not separated by spaces, and the full-text search does not work properly. How can I perform full-text search in Japanese (multi-byte character strings)? I thought about implementing a search engine such as ElasticSearch, but other problems came up. If possible, I would like to do FTS with Postgres. # models.py class Post(models.Model): title = models.CharField(max_length=300) search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["search"])] # update search column Post.objects.update(search=SearchVector('title')) -
Django Show Code in Template if Logged In
In a Laravel Blade template, I can do this to show code only if a user is logged in: @auth <div>Show code only if logged in.</div> @endauth Does Django have a template tag or something similar that does the equivalent? E.g.: {% auth %} <div>Show code only if logged in.</div> {% endauth %} -
Which is better framework Django or Flask? [closed]
I asked this question with my friends but they didn't know about it i am looking for a better framework for Web Development that is coded in Python please help ;/ -
How to add event to multiple dates at the same time in HTMLcalendar
I'm using the htmlcalendar module in Django. When adding an event by setting a period, I want the event to be added at the same time on the relevant date. In the code implemented so far, it is possible to add events only for 1 day. Where do I need to change to get the desired result? models.py class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) leave_date_from = models.DateField(blank=True, null=True) leave_date_to = models.DateField(blank=True, null=True) ----> I just added this field take_over = models.TextField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(leave_date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Leave.objects.filter(leave_date__year=self.year, leave_date__month=self.month, is_deleted=False) cal = f'<table border="0" cellpadding="0" … -
Not Found: /socket.io/
Does anyone have any experience with creating a chat in Django using the python-socketio library? When I launch a Docker container, the backend gives the following error on the Get request: "GET /socket.io/?EIO=3&transport=polling&t=NUzXPq6 HTTP / 1.1" 404 2124 Not Found: /socket.io/ -
I keep getting a 403 forbidden error in Django
Problem 1: I made a notes app. I made a login function, that logs in people. I keep getting an error after I log in and try to create a new note, it is saying "403 forbidden error" in the console. But if I dont log in, it works perfectly. Heres the backend code : @api_view(["POST"]) def login_view(request): data = request.data username = data["username"] password = data["password"] if request.user.is_authenticated: return Response("hpr") else: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response("hpr") return Response("An error occured, please try again later.") this is the login view. I have created a model with a foreign key, that might be the problem too. class Note(models.Model): body = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name="notes", on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] here is the view that creates a note : @api_view(['POST']) def createNote(request): data = request.data note = Note.objects.create( body=data['body'], ) serializer = NoteSerializer(note, many=False) return Response(serializer.data) Problem 2: I also have another doubt. I have a function that gets the notes from the database and displays it. I have made the serialised get all the fields of the note model. But when I try … -
ValueError at /freshleadaction for uploading .csv file in Django
I am stuck on an error in django while uploading a .csv file for fresh leads and I have searched a lot on google for the solution but couldn't find the solution so now decided to upload it so that community can help me. I am displaying the code that I have done so. Models.py: class fresh_leads_model(models.Model): fname = models.CharField(max_length=20) lname = models.CharField(max_length=20) street_number = models.CharField(max_length=20) street_name = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) bedrooms = models.CharField(max_length=20) legal_description = models.CharField(max_length=100) sq_ft = models.CharField(max_length=50) address = models.CharField(max_length=50) orign_ln_amt = models.CharField(max_length=50) prop_value = models.CharField(max_length=50) equity = models.CharField(max_length=255) email = models.CharField(max_length=50) cell = models.CharField(max_length=50) submitted_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(auto_now_add=True) my views.py file for fresh leads upload: @login_required @allowed_users(allowed_roles=['admin']) def upload_fresh_leads(request): get_type = request.GET['type'] lst = [] if request.method == 'POST': leads = Fresh_leads_Form(request.POST, request.FILES) data = request.FILES.getlist('csv') # data = Fresh_leads_Form(request.FILES) # csv_file = request.GET['csv'] # df = pd.read_csv(csv_file) # return HttpResponse(print(df))) # data = [] # message = 2 # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message}) if get_type == '1': if leads.is_valid(): # csv = data['csv'] for d in data: # df = pd.read_csv(d, usecols=['Owner First Name']) # return HttpResponse(df.to_string()) df = pd.read_csv( d, dtype='str', usecols=[ 'Owner First … -
pass field to distinct() in Django
I have a Django web app, using MYSQL. model.py class CourseInfo(TimeStampedModel): code = models.CharField(max_length=20, db_index=True) title = models.CharField(max_length=190) discipline_code = models.CharField(max_length=20, blank=True, null=True) pattern = models.CharField(max_length=120, choices=PRESENTATION_PATTERN, blank=True, null=True, help_text="Presentation Pattern") I want to achieve this filter: query_results_2 = CourseInfo.objects.filter(discipline_id=id).values('discipline_code', 'code', 'title', 'pattern').distinct('discipline_code', 'code') But seems like in mysql, distinct() could not have parameters. How could I achieve this function?---- get 'discipline_code', 'code', 'title', 'pattern' fields but only use 'discipline_code', 'code' for distinct filter. -
How to render contents of two models in a single template where one model is linked by Foreign Key through another in django?
I am trying to create a site for financial purpose. I have two models "Company" and "Reports". Reports model has a foreign key linked to Company. I want to render contents of Company and Reports in a single template in a detail view. When i try to render only one of the model's content is shown not both.. Is there any solution to this? -
Digital Ocean Django Buckets
I am following along on this youtube tutorial: https://www.youtube.com/watch?v=AeCZvXZn5dg&list=PLEsfXFp6DpzRMby_cSoWTFw8zaMdTEXgL&index=77 and I've read this question: DigitalOcean spaces with django code:conf.py AWS_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME="unlock-optimal-performance" AWS_S3_ENDPOINT_URL="https://nyc3.digitaloceanspaces.com" AWS_S3_OBJECT_PARAMETERS={ "CacheControl":"max-age=86400" } AWS_LOCATION="https://unlock-optimal-performance.nyc3.digitaloceanspaces.com" DEFAULT_FILE_STORAGE="cmfitness.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE="cmfitness.cdn.backends.StaticRootS3Boto3Storage" backends.py: from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' and my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'), # https://unlock-optimal-performance.nyc3.digitaloceanspaces.com STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles-cdn") # in production we want cdn MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles-cdn', 'uploads') from .cdn.conf import (AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_STORAGE_BUCKET_NAME,AWS_S3_ENDPOINT_URL,AWS_S3_OBJECT_PARAMETERS,AWS_LOCATION,DEFAULT_FILE_STORAGE,STATICFILES_STORAGE) The Error: Traceback (most recent call last): File "C:\Unlock-Optimal-Performance\manage.py", line 23, in <module> main() File "C:\Unlock-Optimal-Performance\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 194, in handle collected = self.collect() File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 118, in collect handler(path, prefixed_path, storage) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 345, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 255, in delete_file if self.storage.exists(prefixed_path): File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\storages\backends\s3boto3.py", line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 388, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 694, in _make_api_call http, parsed_response = self._make_request( File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 714, in _make_request return self._endpoint.make_request(operation_model, request_dict) … -
Get data from Django to Vue Template
I'm trying to get data from Django to Vuetemplate variables. views.py def index(request): myvar = 1 return render(request, 'index.html',{'myvar':myvar}) in index.html <span> {{ myvar }} </span> Is working, and shows 1, but how can i get this 1/myvar to data inside of the vue instance? var app = new Vue({ el: "#app", data: { // here i need the data/value of myvar } -
How to throw django 404 error as error message on the same page
I am trying to query an instance of a particular model, FoodRedistributor and I would like to throw a pop up error message on the same page if a FoodRedistributor of the given name does not exist. I tried doing Http404 but that redirects me to a 404 page which is not how I would like the user to see the error. Using the messages.info does not give me any output. if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") try: user = FoodRedistributor.objects.get(name=username) except: raise Http404("No food redistributor matches the given query.") -
Different bootstrap(V 4.0) alerts not getting displayed as expected
{% if form.errors %} <div class="alert alert-danger" role="alert"> {% for field in form %} <p>{{field.errors}}</p> {% endfor %} </div> {% endif %} {% if messages %} <div class="alert alert-success" role="alert"> {% for message in messages %} <p>{{message}}</p> {% endfor %} </div> {% endif %} This is a Django project and the above is the order in which I have placed the alerts. The thing is all alerts are getting displayed in as alert-danger, i.e both the form.errors & message are getting displayed within the alert-danger. How can we avoid this isssue? -
heroku failing to process requirements.txt "because these package versions have conflicting dependencies."
I have pushed this project many times before and have made no changes to the requirements.txt file located in the root directory of the project, however. Heroku will no longer accept the same requirements.txt file citing a dependency issue Heroku still opens the last valid push to allow me to "pip freeze" pushed heroku requirements.txt appnope==0.1.2 asgiref==3.4.1 backcall==0.2.0 backports.entry-points-selectable==1.1.0 blis==0.7.4 catalogue==2.0.6 certifi==2021.5.30 charset-normalizer==2.0.4 ChatterBot==1.0.4 chatterbot-corpus==1.2.0 click==8.0.1 colorgram.py==1.2.0 cymem==2.0.5 debugpy==1.4.3 decorator==5.1.0 distlib==0.3.3 dj-database-url==0.5.0 Django==3.2.8 django-filter==2.4.0 django-heroku==0.0.0 django-simple-chatbot==0.0.9 django-widget-tweaks==1.4.8 djangorestframework==3.12.4 en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl entrypoints==0.3 filelock==3.3.0 future==0.18.2 greenlet==1.1.2 gunicorn==20.1.0 heroku==0.1.4 httpie==2.4.0 huggingface-hub==0.0.12 idna==3.2 ipykernel==6.4.1 ipython==7.28.0 ipython-genutils==0.2.0 jedi==0.18.0 Jinja2==3.0.1 joblib==1.0.1 jupyter-client==7.0.3 jupyter-core==4.8.1 line-bot-sdk==1.20.0 MarkupSafe==2.0.1 mathparse==0.1.2 matplotlib-inline==0.1.3 murmurhash==1.0.5 nest-asyncio==1.5.1 nltk==3.6.2 numpy==1.21.2 packaging==21.0 parso==0.8.2 pathy==0.6.0 pexpect==4.8.0 pickleshare==0.7.5 Pillow==8.3.2 Pint==0.17 pipenv==2021.5.29 platformdirs==2.4.0 preshed==3.0.5 print==1.3.0 prompt-toolkit==3.0.20 psycopg==3.0b1 psycopg2==2.9.1 psycopg2-binary==2.9.1 ptyprocess==0.7.0 pydantic==1.8.2 Pygments==2.10.0 pymongo==3.12.0 pyparsing==2.4.7 PySocks==1.7.1 python-dateutil==2.7.5 pytz==2021.3 PyYAML==5.4.1 pyzmq==22.3.0 regex==2021.8.28 requests==2.26.0 requests-toolbelt==0.9.1 sacremoses==0.0.46 six==1.16.0 smart-open==5.2.1 spacy==3.1.3 spacy-alignments==0.8.3 spacy-legacy==3.0.8 spacy-transformers==1.0.6 SQLAlchemy==1.2.19 sqlparse==0.4.2 srsly==2.4.1 textblob==0.15.3 thinc==8.0.10 tokenizers==0.10.3 torch==1.8.1+cpu torchvision==0.9.1+cpu tornado==6.1 tqdm==4.62.2 traitlets==5.1.0 transformers==4.9.2 turtle==0.0.1 typer==0.4.0 typing-extensions==3.10.0.2 urllib3==1.26.6 virtualenv==20.8.1 virtualenv-clone==0.5.7 wasabi==0.8.2 heroku now tells me the following error when i try to deploy my latest version using identical requirements.txt files. The conflict is caused by: The user requested PyYAML==5.4.1 chatterbot-corpus 1.2.0 depends on PyYAML<4.0 and >=3.12 To fix this you could …