Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create HTML/JS matrix in django template
I have a view which returns this data in dictionary form: {('ACCOUNTS', 'Staff'): 8, ('ACCOUNTS', 'TOA'): 3, ('HR', 'Officer'): 4, ('HR', 'Staff'): 1} I need to convert this dictionary to a matrix in django template. something like this: please note the dictionary could be any longer. -
Why am I getting django.db.models error telling me I have no attribute for TextChoices in Django (3.1.6) and Python(3.8)?
thanks so much for reading. I've got this running on my computer no problem. It's working on my VS on Windows 10. But this error keeps coming up, it looks like TextChoices is no longer usable? AttributeError: module 'django.db.models' has no attribute 'TextChoices' I'm putting it u0p on PythonAnywhere, Python 3.8, and Django 3.1.6 I am still new at this, so please forgive me1 My issue is with the TextChoices, here is the full error: Traceback (most recent call last): File "/home/sandorf/project/listings/models.py", line 6, in <module> class Listings(models.Model): File "/home/sandorf/project/listings/models.py", line 7, in Listings class Country(models.TextChoices): AttributeError: module 'django.db.models' has no attribute 'TextChoices' This is my models.py in the app directory from django.db import models from django.utils.timezone import now from datetime import datetime # Create your models here. class Listings(models.Model): class Country(models.TextChoices): USA = "USA" CHINA = "China" CANADA = "Canada" INDIA = "India" UK = "UK" EUROPE = "Europe" MIDDLE_EAST = "Middle East" OTHER = "Other" class Topic(models.TextChoices): STATISTICS = "Statistics" VACCINE = "Vaccine" NEW_STRAINS = "New Strains" LOCKDOWN = "Lockdown" COVID_NEWS = "Covid News" title = models.CharField(max_length=745) link = models.CharField(max_length=745) summary = models.TextField(Null=False) country = models.CharField( max_length=100, choices=Country.choices, default="Country.OTHER") topic = models.CharField( max_length=100, choices=Topic.choices, default="Topic.COVID_NEWS") list_date = models.DateTimeField(default=now) … -
Display the error_messages under the fields
I'm using this package for my form https://github.com/KuwaitNET/djvue but anyway it's like a general question, I've wrote the following method to validate my phone number field def validate_phone_number(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): self.fields["phone_number"].error_messages.update({"ph":"Wrong"}) raise ValidationError(_(u'The phone number entered is not valid.')) return value and it works just fine because in my Model: def serve(self, request, *args, **kwargs): if request.method == "POST": data = json.loads(request.body) serializer = ContactUsSerializer(data=data) if serializer.is_valid(): ticket_number = serializer.save() return JsonResponse({"ticket_number": ticket_number}) else: return JsonResponse(serializer.errors) ctx = self.get_context(request, *args, **kwargs) ctx["serializer"] = ContactUsSerializer() request.is_preview = getattr(request, "is_preview", False) return TemplateResponse( request, self.get_template(request, *args, **kwargs), ctx ) and actually when I enter an invalid phone number I'm getting a JsonResponse with the error: 0: "The phone number entered is not valid." which is great, but how can I display the updated error message below the phone_number field?? it looks like despite the errors are being updated the displaying is not, should I use Vue or something to achieve that? knowing that the package I'm using does so: <span class="help-block text-danger" v-for="error in errors" :key="error">{( error )}</span> but I'm not sure how and where they render the error, so I want maybe a pure … -
How to send live video captured from opencv in django to aws kinesis-video-streams putmedia endpoint?
To achieve: capture the live feed of a camera in web browser using OpenCV and send it to AWS Kinesis-video-stream(an aws service) using PUT_MEDIA(end_point). Have referred Amazon AWS Kinesis Video Boto GetMedia/PutMedia and made a few changes to capture from camera. HTML Code to display user stream (video captured from webcam): <html> <body> <video autoplay="true" id="myVideo"></video> </body> </html> ''' **views.py** def get_endpoint_boto(): import boto3 client = boto3.client('kinesisvideo','us-east-2',aws_access_key_id = your_env_access_key_var ,aws_secret_access_key = your_env_secret_key_var) response = client.get_data_endpoint( StreamName=your_stream_name, APIName='PUT_MEDIA' ) print(response) endpoint = response.get('DataEndpoint', None) print("endpoint %s" % endpoint) if endpoint is None: raise Exception("endpoint none") return endpoint def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def get_signature_key(key, date_stamp, regionName, serviceName): kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, 'aws4_request') return kSigning def get_host_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):] return str(retv) def get_region_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):].split('.')[2] return str(retv) class gen_request_parameters: def __init__(self): self._data = '' if True: print('True') cap = cv.VideoCapture(0) cap.set(5,60) if not cap.isOpened(): exit() ret, frame = cap.read() request_parameters = cap.read() self._data = request_parameters self._pointer = 0 self._size = len(self._data) def __next__(self): print('next') if self._pointer >= self._size: raise StopIteration left = self._size - self._pointer … -
In a journal app, author adding and requests with django
With the following code, i could make a simple journal app.. but i don't know how to control the relations between authors and editor. The thing i want, The Editor must add a author to own journal. and also, authors write an article only to journal to which he/she added. Also i want, authors can send editors request for authorship. How can i construct such a system? class Journal(models.Model): journal_editor = models.ForeignKey(User,on_delete=models.CASCADE,related_name="journal_editor",default=1) unique_id = models.CharField(max_length=100, editable=False, null=True) journal_title = models.CharField(max_length=250, verbose_name="Dergi Adı", blank=False, null=True) slug = models.SlugField(null=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Dergi" verbose_name_plural = "Dergiler" ordering = ["-created"] def __str__(self): return "%s" % (self.journal_title) def get_unique_slug(self): x = 0 slug = slugify(unidecode(self.journal_title)) new_slug = slug while Journal.objects.filter(slug=new_slug).exists(): x += 1 new_slug = "%s-%s" % (slug, x) slug = new_slug return slug def save(self, *args,**kwargs): if self.id is None: new_unique_id = str(uuid4()) self.unique_id = new_unique_id self.slug = self.get_unique_slug() else: journal = Journal.objects.get(slug=self.slug) if journal.journal_title != self.journal_title: self.slug = self.get_unique_slug() super(Journal, self).save(*args,**kwargs) class Article_of_Journal(models.Model): author_of_article = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name="author_of_article") journal_name = models.ForeignKey(Journal,on_delete=models.CASCADE,default=1,related_name="journal_name") unique_id = models.CharField(max_length=100,editable=False,null=True) article_title = models.CharField(max_length=250,verbose_name="Başlık",blank=False,null=True) article_content = RichTextUploadingField(null=True,blank=False,verbose_name="İçerik") slug = models.SlugField(null=True,unique=True,editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Makale" verbose_name_plural … -
How to iterate ManyToMany filed in serializer class
I have this Event model: # models.py class Event(models.Model): name = models.CharField(max_length=200)) user = models.ManyToManyField(User)) This is my ListCreateAPIView class: class EventListView(LoginRequiredMixin, generic.ListView): model = Event This is my ListCreateAPIView class: class Events(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Event.objects.all() serializer_class = EventSerializer This is my serialiser class: #serializers,py class EventSerializer(serializers.ModelSerializer): class Meta: fields = ( ‘id', 'name', 'user', ) model = Event And this is my REST request response: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "name": "My event1", "user": [ 1, 4 ], "registered": true // <—- I NEED THIS }, { "id": 2, "name": "Other event", "user": [ 2, 4, 6 ], "registered": false // <—- I NEED THIS } ] } What I am gonna need in REST response is property “registered”, which will contain true or false if current user is registered on particular event or not. My approach was to control if current user is in list of users of event. I tried to get this information in serialiser class this way: #serializers,py class EventSerializer(serializers.ModelSerializer): registered = serializers.SerializerMethodField(‘_user’) def _user(self, obj): request = getattr(self.context, 'request', None) if request.user in self.user: return True else: return False class Meta: fields = ( … -
Django: Parent model contain a list child model like a custom template
I'm a newbie Django. Example: I have a parent model Project, child model Phase like this: class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) ... def __str__(self): return self.name class Phase(models.Model): phase_id = models.AutoField(primary_key=True) phase_name = models.CharField(max_length=300, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) ... def __str__(self): return self.phase_name Question 1: How can I create a custom template is a list of Phase when user create new Project? New Project A: Phase 1 Phase 2 Question 2: And when user change a custom list of Phase, how can I store list and reuse it with another new Project? List Phase Custom: (edit phase: + Phase 3, + Phase 4, - Phase 2) Phase 1 Phase 3 Phase 4 New Project B: Phase 1 Phase 3 Phase 4 Any link references or document relate it? Thank you! -
How to generate models with another model's primary key as the model name in Django
I am working on a django project where the website will let the user to register for an event and let them check in. models.py contains: class Event(models.Model): eventName = models.CharField(max_length=264, unique=True) # Event Name eventDescription = models.TextField() # About the Event I want the program to generate more models with the eventName attribute row values from Event model. Example: Consider that Event model consists of the following row values: CodeChef | CodeChef annual Event GSOC | Google Summer Of Code Then I want the following models to be automatically generated with some predefined attributes (number of attendees, EventStatus): class CodeChef (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) class GSOC (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) PS: I am a beginner to Django. -
Uncaught TypeError: Cannot read property 'replace' of undefined using PostgreSQL database and django
I am getting the following error when I click on a marker deployed from my PostgreSQL database onto a google map. I am expecting an info modal to pop up and show some information. The information that should show up is being posted to the database from a form on my website via an AJAX call. The marker shows up in the correct position but I get this error when I click it: Uncaught TypeError: Cannot read property 'replace' of undefined Here is my AJAX call that posts the data: const commitNewCafe = function () { let name = document.getElementById("venueName").value; let type = document.getElementById("venueType").value; let address = document.getElementById("venueAddress").value; let latitude = parseFloat(document.getElementById("latitude").innerHTML); let longitude = parseFloat(document.getElementById("longitude").innerHTML); $.ajax({ type: 'POST', url: '/add_cafe/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'venuename': name, 'venuetype': type, 'venueaddress': address, 'latitude': latitude, 'longitude': longitude }, success: function(data) { console.log("Data sent"); } }); } Here is the views.py function that processes it for the database: def add_cafe(request): if request.method == "POST": new_obj = mapCafes() new_obj.cafe_name = request.POST.get('venuename') new_obj.cafe_address = request.POST.get('venueaddress') new_obj.venue_type = request.POST.get('venuetype') new_obj.cafe_long = float(request.POST.get('longitude')) new_obj.cafe_lat = float(request.POST.get('latitude')) new_obj.save() return render(request, 'testingland/addcafe.html') And here is the ajax call that retrieves the data for the marker modal box: $.ajax({ type: … -
how to reverse url with pk post django
hi i am creating a django blog in which i am adding a comment section,all stuff worked fine. but after adding comments i want to redirect to that perticular post in which i wanted to add comment views.py class add_comment(CreateView): model = comments fields = ['comment'] template_name = 'forum_app/add_comment.html' success_url = reverse_lazy('post_detail',) def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls.py from . import views from .views import post_detail,add_comment urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), path('<int:pk>/',post_detail.as_view(),name='post_detail'), path('add_comment/<int:pk>/',add_comment.as_view(), name='add_comment') ] all i want to do is once i click submit it should reverse to the same post which i wanted to add comments simple post_detail asking for pk but not able to integrate pk in this... help is appreciated -
How to warmup cache view as login user in Django?
I want to warmup cached View from scheduled management command. I have to be logined when doing request to View. What is the best practice to login as user and do get request to View? I am thinking about two ways: Use requests: request = requests.session() response = request.get(login_url) token = response.cookies['csrftoken'] data={'username':'username@username.ru', 'password': 'pass','csrfmiddlewaretoken':token} response = request.post(login_url, data=data) response = request.get(target_url) Use test.Client() and login option. What is better? Or maybe the best option exists? -
Update Django model based on the row number of rows produced by a subquery on the same model
I have a PostgreSQL query which updates the global_ranking field of each row, based on the row number of that row as computed by a subquery which takes that same table and sorts it according to another column called rating. Additionally, the update is partitioned, so that the ranking of each updated row is relative to only those rows which belong to the same language. In short, I'm updating the ranking of each player in a word game (why player statistics have a language field), based on their current rating. The working PostgreSQL query looks like this: UPDATE stats_userstats SET global_ranking = sub.row_number FROM ( SELECT id, row_number() OVER ( PARTITION BY language ORDER BY rating DESC ) AS row_number FROM stats_userstats ) sub WHERE stats_userstats.id = sub.id; I'm using Django, and it'd be fun to learn how to express this query using the Django ORM, if possible, before resorting to running a raw query. It seems like Django has all the parts that are necessary to express the query, including the ability to use PostgreSQL's row_number() windowing function, but my current attempt updates all rows ranking with 1: from django.db.models import F, OuterRef, Subquery from django.db.models.expressions import Window from … -
Why there is a lag between Django and Gunicorn?
I have my production server (RHEL 7) setup with the following Nginx -> Gunicorn -> Django. Below are the logs from django (removed log messages and modules info for safety reasons). { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,371" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,611" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,852" <removed for safety reasons> } It is clear that the time taken to process a request and respond is Approx 1-2 sec Below is the access log entry in gunicorn - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.0" 200 18496 "<domain name removed for safety reasons>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" and Below is the entry log in Nginx <ip removed for safety reasons> - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.1" 200 18496 "<domain name removed for safety reasons>>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" "-" "-" I assumed that the template rendering is taking time, however this template is a simpler one and shouldn't take more … -
Django: celery showing different status for the same task
I've a django app with two celery tasks, say task1 and task2. task1 gets triggered on a POST request from the frontend and the request has to sent back the task id so the frontend can poll its status later. task2 is supposed to run after task1 succeeds, asynchronously. Here're my task definitions: @shared_task(ignore_result=False) def task1(pk: int): # retrieve object matching pk return task1_func(obj) @shared_task(ignore_result=False) def task2(task_id: int): task = AsyncResult(task_id) while not task.ready(): logger.info("status {}".format(task.status)) time.sleep(1) return task2_func() Here's how I'm triggering them inside my views.py: class MyView(viewsets.ModelViewSet): def create(self, request): # create object task = task1.delay(obj.pk) task2.delay(task.id) #breakpoint return Response(task.id, status=status.HTTP_200_OK) Now when I try checking the status at the breakpoint, it shows success: In [1]: task.id Out[1]: '97f8d150-de04-4848-a400-3882988c833c' In [2]: task.status Out[2]: 'SUCCESS' In [3]: AsyncResult(task.id).status Out[3]: 'SUCCESS' But the code inside the task2 never gets executed because the status of task1 inside task2, never changes from PENDING. What am I doing wrong? Clearly my results are being stored and accessible but for some reason I cannot see the change in status from within another task. I cannot chain the tasks because I've to send the first task's id to the frontend. -
How exactly should JWT-based authentication be implemented in Django (drf and simplejwt)?
I am struggling to understand exactly how JWT-based authentication should be implemented in Django (I am using simplejwt). I am just a beginner, so please brace yourselves for some silly questions. The rest-framework-simplejwt documentation is very minimal and does not provide enough detail for a newbie like me. path('token/obtain', jwt_views.TokenObtainPairView.as_view(), name='token_create'), path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), So, I've created the paths in my urls.py as suggested by the official documentation. Where do I go from here? I guess my confusion comes from the fact that I am not sure where exactly in the code I have to issue my tokens. Let's say, I am logging in the user. So, in order to obtain the token, do I have to send a request to the 'token_create' endpoint from inside my view? Or do I have to somehow indicate it in one of my serializers? What about the 'refresh_token' endpoint? Is there a specific method that I need to use? Then, what do I do with the token once it has been issued? Clearly, I shouldn't save it in the database since it defeats the entire purpose of using JWTs in the first place. From my understanding, I should attach it to the headers … -
How to display single/particular data record from database -django
I want to display a particular data record from the database of a person who is logged in to the website. I have a default primary key in the migration. Other than that I don't have any of the primary or foreign keys. Below is the models.py and template codes. models.py class Ticket(models.Model): Email = models.CharField(max_length=40) to = models.CharField(max_length=40) cc = models.CharField(max_length=50) subject = models.CharField(max_length=25) class Meta: db_table = 'ticket' def __str__(self): return self.Email Following is the views which I had used before, that display's the whole data from the database. Views.py def ticket(request): ticket = Ticket.objects.all() return render(request, 'web/ticket.html', {'ticket':ticket}) But I want to display data of the respective mail id ticket.html {% for ticket in ticket %} <fieldset id="first"> <label for="From"><b>From</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="From" name="From" style="width:100%" value="{{ ticket.Email }}" required> <br> <br> <label for="To"><b>To</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="To" name="To" style="width:100%" value="{{ ticket.to }}" required><br> <br> <label for="Cc"><b>Cc</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Cc" name="Cc" style="width:100%" value="{{ ticket.cc }}" required><br> <br> <label for="Subject"><b>Subject</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Subject" name="Subject" style="width:100%" value="{{ ticket.subject }}" required><br> <br> </fieldset> … -
Scraping jobs from PDF in india
I am facing an issue with PDF. I have to scrape the jobs from pdf file. Different pdfs are in different formats. I can scrape the data from pdf but, I need to identify which is a job title, job description..e.t.c.I am unable to do that.Can you guys suggest any solution to this issue? I need a solution in python. -
(1170, "BLOB/TEXT column 'BS_ID' used in key specification without a key length") Error while shifting my Django Database from Sqlite3 to mySQL
I have recently being try to change my Django database from sqlite3 to MySQL and while running the migrations I'm getting this error for the text field which is a primary key, its necessary to have it as a primary key because I have to use it for foreign key. Please share what changes do I need to make in my models to make this migration to MySQL successful. BS_ID = models.TextField(max_length=20,unique=True)- this field is the cause of the error. -
Pass the value of dropdown to sql query and fetch data and display in form of checkbox using Django Python
So i have a code which should get the value of dropdown selected value and pass it to a sql query fetch the result and pass it to another class , Since am new to django and am not really able to find what is the problem with the code . Can anyone kindly help me Posting the code <form enctype="multipart/form-data" action="{% url 'files' %}" method="POST"> {% csrf_token %} {{SnippetForm|materializecss}} <br> <table class="table form-table table-bordered table-sm"> <tbody> {% for form_data in formset %} <tr class="item"> <td> {{ form_data.server|materializecss }} </td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} <br> <button type="reset" class="waves-effect waves light btn-large">Reset</button> <button type="submit" class="waves-effect waves light btn-large">Submit</button> </form> Here is the Index.html and the SnippetForm contains textbox Model.py # Create your models here. class Snippet(models.Model): customer = models.CharField(max_length=100, choices=customer_list) environment = models.CharField(max_length=100, choices=environment_list) def __str__(self): return self.customer class Meta: db_table = "snippet" Value = Snippet() cursor.execute("select distinct(VMName) from Inventory where customer='"+str(Value)+"' and status='Active'") records2 = cursor.fetchall() for i in range(len(records2)): server_choices[records2[i][0]] = records2[i][0] server_list = tuple([(str(k), v) for k, v in server_choices.items()]) class Files(models.Model): files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) snippet = models.ForeignKey(Snippet, related_name="files", on_delete=models.CASCADE) def __str__(self): return str(self.snippet) class … -
OrderForm' object has no attribute 'get' via request.post
I've created an orderform and was trying to extract information from the form. However, each time when i called for forms.get("firstname") or anything, i will face the error that the object has no attribute 'get" even though it is a form. more specifically, the error is "AttributeError: 'OrderForm' object has no attribute 'get'" Here is the relevant code: in models.py: class BaseModel(models.Model): eid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: abstract = True @classmethod def get_or_none(cls, **kwargs): try: return cls.objects.get(**kwargs) except cls.DoesNotExist: return None class Order(BaseModel): itemname = models.CharField(max_length =100, default="") firstname = models.CharField(max_length = 20) lastname = models.CharField(max_length = 20) email = models.EmailField() phone = PhoneNumberField(null=False, blank=False) comments = models.TextField() delivery = models.BooleanField(default=False) def __str__(self): return str(self.eid) in forms.py: class OrderForm(forms.ModelForm): itemname = forms.ModelMultipleChoiceField(queryset=Post.objects.filter(title__contains="Bae"), required=True) class Meta: model = Order fields = ('itemname', 'firstname', 'lastname', 'email', 'phone','delivery', 'comments') labels = {'itemname': 'Order Item', 'firstname': 'First Name', 'lastname':"Last Name", 'email':"Email", 'phone':"Phone Number", 'delivery':'Deliver?', 'comments':'Comments'} in views.py. This is where the error occurs: def order(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) item_selected = form.get('itemname') order.itemname = item_selected order.save() return render(request, 'Reddit_app/order_thankyou.html') else: form = OrderForm() return render(request, 'Reddit_app/order_from_post.html', {"form": form}) finally, the … -
Pycharm Django remote execution trying to use local path
I created a Django project in Pycharm, and configured for remote execution. Pycharm happily uploads the local project to the remote VM. However, when I try to debug/execute manage.py, or another "hello world" kind of Python script, it appears that the remote python is being handed the path to manage.py, etc. on my local machine, not the path to manage.py, etc. on the remote machine. I've successfully create and remotely executed multiple "Pure Python" Pycharm projects. I am reasonably familiar with Pycharm, but not so much with Django, and particularly not experienced running Django under Python. Any suggestions as to what I might be doing wrong are appreciated Config: Pycharm 2019.3.4 Professional MacOS Catalina. The Pycharm console output follows. ssh://xxx@xxx:22/usr/local/bin/python3.9 -u /home/xxx/.pycharm_helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 0.0.0.0 --port 43395 --file /Users/xxx/PycharmProjects/etlworkflow/manage.py bash: line 0: cd: /Users/xxx/PycharmProjects/etlworkflow: No such file or directory pydev debugger: process 6418 is connecting Connected to pydev debugger (build 193.6911.25) Traceback (most recent call last): File "/home/xxx/.pycharm_helpers/pydev/pydevd.py", line 1434, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/home/xxx/.pycharm_helpers/pydev/_pydev_imps/_pydev_execfile.py", line 11, in execfile stream = tokenize.open(file) # @UndefinedVariable File "/usr/local/lib/python3.9/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/Users/xxx/PycharmProjects/etlworkflow/manage.py' -
Django: AttributeError: 'User' object has no attribute 'get'
I'm getting AttributeError: 'User' object has no attribute 'get' in Django, I am trying to get the favorite movie genres of the user. My form looks like this: class GenresForm(forms.ModelForm): firstGenre = forms.CharField(label="What is your favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) secondGenre = forms.CharField(label="What is your second favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) thirdGenre = forms.CharField(label="What is your third favorite genre?", widget=forms.Select(choices=GENRE_CHOICES)) class Meta: model = Favorites fields = ["firstGenre", "secondGenre", "thirdGenre"] My view: def genres(request): user = request.user if request.method == "POST": form = GenresForm(request.POST) if form.is_valid(): genres = form.save(commit=False) genres.user = request.user genres.save() return redirect("/home") else: form = GenresForm(request.user) return render(request, 'core/genres.html', {"form":form}) and my Model class Favorites(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstGenre = models.CharField(max_length=50) secondGenre = models.CharField(max_length=50) thirdGenre = models.CharField(max_length=50) -
count of likes is not showing in python django .... I don't know why .. Can someone help me
registration and login page is working properly but mine count of likes is not showing in django... I don't know why... Can somebody help me to find this error... It will be the great help... Thank You!! 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} def __init__(self, *args, **kwargs): stuff = get_object_or_404(Post, id = self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) 2.Urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), ] 3.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User) @property def total_likes(self): return self.likes.count() def __str__(self): return self.title + " by " + self.author 4.data.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, … -
How can I implement AJAX live search in my Django Application?
I am looking to create a recipe app with a live search feature where you will type into the search bar located at the top of the home page, and it should filter down the list of recipes that are displayed underneath (located in the partial_home.html file). What I am expecting to see is that when I input any character or string of characters, the search icon should start blinking, and then after a short delay (about 700 miliseconds), the recipes should fade out and the fade in with a filtered list. Currently I am able to have the search icon blink when inputting text into the search bar, indicating that the js file is being read, however no changes are made to the recipes and nothing is fading in/out. If I add in the following tail ".../?q="chicken" for example, I am able to load the page with filtered recipes for all recipes with "chicken" in the title, however it is not occurring asynchronously. Would anyone know what the issue is in my code? I am currently using Django 3.1.2 main.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" … -
CSRF cookie not set: POST from Javascript to separate Django project
I'm developing two separate django (version 3.1) projects. I keep getting a "403: CSRF cookie not set" error and have no idea what the problem is. Project 1 is running on an Apache server & takes POST requests containing JSON data & sends back a JSON response. Project 2, running on localhost, sends the POST via Javascript XMLHttpRequest() function to Project 1. This question seems to be having the same problem as me, but I'm trying to send info between different URL's (more specifically, POST from localhost:8000, eventually url.com, to engine.url.com) and I don't think that user's solution will work for me. I've tried using the @csrf_exempt decorator on Project 1 views.py, and it works just fine. However, personally identifying information might be sent between the two, so I want to make sure things are secure. A csrf cookie is best practice if I'm not mistaken, so I have the decorator @ensure_csrf_cookie before my view. I've tried everything I could find online to fix the problem. In Project 1 settings.py, I've included 'corsheaders' in my INSTALLED_APPS, 'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE and have the following code at the end of the file: CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CORS_ALLOWED_ORIGINS …