Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django select filtered related object
I have 3 models: class ForumTopic(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=100) class ForumMessage(models.Model): topic = models.ForeignKey(ForumTopic, on_delete=models.CASCADE) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) class ForumMessageVote(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) message = models.ForeignKey(ForumMessage, on_delete=models.CASCADE) vote = models.IntegerField(default=0) I want to select all ForumMessage for specific ForumTopic and attach to result of this query ForumMessageVote filtered by specific User and current ForumMessage. How I can do this? -
Duplicated element after Ajax run
I am trying to Auto-complete form fields using Ajax and Jquery. First I used Django and the views.py function is: def CreateWellMon(request): if request.method == 'POST': form = SurveillanceDesPuits_F(request.POST or None) if form.is_valid(): form.instance.author = request.user form.save() return redirect('WellMonitor') else: try: PUITS_id = request.GET.get('PUITS') record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1] record2 = SurveillanceDesPuits.objects.get(id= record[0].id) form = SurveillanceDesPuits_F(instance=record2) return render(request, 'measure/Surveill_Wells/Add_wellMntr2.html', {'form': form}) except: record2 = SurveillanceDesPuits.objects.all().first() form = SurveillanceDesPuits_F(instance=record2) return render(request, 'measure/Surveill_Wells/Add_wellMntr2.html', {'form': form}) So here I just selected the last record from the database at first. After when the user chooses a Well it reloads the last record of the element. my HTML page code is: {% extends 'Home/base2.html' %} {% block content %} {% load crispy_forms_tags %} <div class="w3-panel w3-border w3-light-grey w3-round-large sizeA"> <h2>Well Information</h2> <h2 class="border-bottom pb-1 mb-3"><b>Add New montoring record 3</b></h2> </div> {% if form %} <div class="border p-3 mb-3 mt-3 w3-round-large w3-light-grey border-dark"> <form method="POST" id="SurveillanceDesPuits_F" data-record-url="{% url 'Add_wellMntr' %}"> {% csrf_token %} <!-- form from views.py--> <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div id= "PUITS" class="form-group col-md-3 mb-0"> {{form.PUITS|as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.CS |as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.MODE|as_crispy_field}} </div> <div class="form-group col-md-3 mb-0"> {{ form.SITUATION |as_crispy_field}} </div> </div> <div … -
Cannot assign "'somedata'": "otherdatal" must be a "" instance.`
is it possible to insert the session value to the foreign key.? here i have 2 models class candidate(models.Model): fname=models.CharField("First name ",max_length=20,default="") lname=models.CharField("Last name ",max_length=20,default="") email=models.EmailField("Email ",max_length=254,primary_key=True) password=models.CharField("Password ",max_length=100,default="") def __str__(self): return self.email #self.fname+" " +self.lname here iam taking the email from above model as a session and trying to put this session value to the foreign key field of the below model class canDetails(models.Model): candEmail=models.ForeignKey(candidate,on_delete=models.CASCADE) location=models.CharField("location ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/canDetails/") def __str__(self): return self.candEmail but here i am getting error like Cannot assign "'cb@gmail.com'": "canDetails.candEmail" must be a "candidate" instance. i am trying to get all the details from candidate model and candDetails model at once thats why i using pf and fk here,so is it the right way i am following...? how can i deal with this ? any suggestions pls.? -
Heroku / Redis Connection error on Python/Django Project
I'm trying to set up django so it send automatic email when a certain date in my models i reached. However i setup a Heroku-Redis server and am trying to connect to it. I created a simple task to test out if celery is working but it always returns the following error: Error while reading from socket: (10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None) I setup celery according to the website: celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'incFleet.settings') app = Celery('incFleet') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Tasks.py import datetime from celery import shared_task, task from time import sleep from .models import trucks from datetime import datetime @shared_task() def sleepy(duration): sleep(duration) return 0 #@shared_task() #def send_warning(): And my settings.py # Celery Broker - Redis CELERY_BROKER_URL = 'redis://:p0445df1196b44ba70a9bd0c84545315fec8a5dcbd77c8e8c4bd22ff4cd0a2ff4@ec2-54-167-58-171.compute-1.amazonaws.com:11900/' CELERY_RESULT_BACKEND = 'redis://:p0445df1196b44ba70a9bd0c84545315fec8a5dcbd77c8e8c4bd22ff4cd0a2ff4@ec2-54-167-58-171.compute-1.amazonaws.com:11900/' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' -
Why is this django annotated queryset with rawSQL values not set but raw query returns results?
The problem I have is the django queryset does not contain the data from raw sql query interfaces = Interface.objects.filter( membership__in=membership_set ).annotate( utilisation=RawSQL( 'SELECT utilisation FROM interfacestat WHERE interface.name = interfacestat.ifl AND interfacestat.date = "%s"' ,(recent_date,) ), ).order_by('name') So I am using a RawSQL expression to populate the utilisation field. I check the raw sql with print(interfaces.query) and run that directly on MySQL. It returns results for the utilisation field on a few records - however when I loop through the queryset the utilisation field is always unset (None). eg. interfaces[0].__dict__ {'_state': <django.db.models.base.ModelState object at 0x109b1fdf0>, 'id': 230083, 'name': 'ae1.3216', ...'utilisation': None} Looping through: ipdb> all = interfaces.values() ipdb> for item in all: print(item.get('utilisation')) None None None None None None None None None None None None None -
Heroku error while deploying. error: RPC failed; HTTP 504 curl 22 The requested URL returned error: 504
I had no problems in the past with the deployment to Heroku via HTTP transport, but recently I am unable to deploy. This is the error I am getting: Enumerating objects: 58668, done. Counting objects: 100% (57434/57434), done. Delta compression using up to 16 threads Compressing objects: 100% (16705/16705), done. Writing objects: 100% (57124/57124), 50.77 MiB | 76.23 MiB/s, done. Total 57124 (delta 44149), reused 52353 (delta 40249) error: RPC failed; HTTP 504 curl 22 The requested URL returned error: 504 fatal: the remote end hung up unexpectedly fatal: the remote end hung up unexpectedly I've tried switching to SSH transport and it works, but Heroku is retiring SSH transport, so I need to figure out this error. Also I tried to change the postBuffer according to atlassian's page, but I got the error again. git config --global http.postBuffer 157286400 Does anybody have an idea how to solve this? There are very few resources on the web that I found, and none of them are fixing the problem. -
Django-q how to delete scheduled tasks from code
I use django-q to schedule a periodic task associated an entry in my model Repository (code here after). But when I delete a Repository entry, the associated Schedule entry is not deleted, and so the django-q jobs associated is not cancelled. Any idea ? from django_q.models import Schedule class Repository(models.Model): id = models.AutoField(primary_key=True) [...] scheduled_scan = models.ForeignKey(Schedule, on_delete=models.CASCADE, default=None, blank=True, null=True) thanks a lot -
Django Channels full image path
If I want to get full image path in django rest I just need to write something like this: def get(self, request) qs = SomeModel.objects.all() serializer = SomeSerializer(qs, many=True, context={'request': request}) return Response(serializer.data) And then the result will be { "image": "http://127.0.0.1:8000/media/someimg.png" } But there is no request django channels. I know that there is self.scope but it can't be used like request. Is there any option to get request or even some class with build_absolute_uri() function inside consumer? Here is some of my code: Consumers: # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user = self.scope['user'] chat_room = ChatRoom.objects.get(pk=self.room_name) message = Message.objects.create(author=user, chat_room=chat_room, content=message).pk # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] serializer = WSMessageSerializer(Message.objects.get(pk=message)) # Send message to WebSocket self.send(text_data=json.dumps(serializer.data)) WSMessageSerializer: class WSMessageSerializer(serializers.ModelSerializer): author = FriendSerializer() class Meta: model = Message fields = ['id', 'author', 'content', 'created_at'] FriendSerializer: class FriendSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ['id', 'username', 'first_name', 'last_name', 'full_name', 'pfp'] -
Clean way to customize forms based on user's group in Django
I want to customize my model's forms based on user's group. The customization that I am talking about are small, but to give you an idea, my "customizations" would be something like : users within GroupA would have a BooleanField with True as default, even though default is False for others users within GroupB would have a CharField (input text) hidden (not changeable) users within groupC would have not the same options as others for a CharField with options (different options in select) ... Currently, I actually achieved to do this by doing a mix of logic in my views.py and in my forms.py. But I don't really like to mix logic in 2 different files, so I came to ask your opinion about which is the best (cleanest) way in your opinion and how to achieve it. Here are the 2 technics that I think of: 1. Creating a form for each group in forms.py. This would be the cleanest way imo. By creating a form for every group (MyModelGroupAForm(ModelForm), MyModelGroupBForm(ModelForm), ...) , I can easily change a field/input/... in my forms.py file everytime that a change is requested and/or a group is created. Then, all I have to … -
django filter for NOT IN as lookup_expr
We can make the django filter with "in" expression sending comma separated string. Such as import django_filters class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter): pass class BookFilter(django_filters.FilterSet): author = NumberInFilter(field_name="author__id", lookup_expr="in") However, I was looking for way to send comma separated query-data and get response which do not have the query-data. something like class BookFilter(django_filters.FilterSet): author = NumberInFilter(field_name="author__id", lookup_expr="not_in") Definitely there is nothing like "not_in". Can you please give me a solution to achieve this? -
How can check availability domain name by using Python?
I'm trying to make a script that returns unregistered domains. How can I find an available domain name? -
Django REST framework how to create new User?
I'm now trying since two days getting stupid POST requests into my Django application using the Django REST framework but fir some reason i always fail getting a request trough. Either I get a permission error when creating a class based view. if I create a function based view I always run into validation error and im kind of frustrated about the complexity of DRF. Have a look at the following view to create a User object: views.py @api_view(['GET', 'POST']) @permission_classes([AllowAny]) def user_create(request): if request.method == 'POST': print(request.data) serializer = CreateUserProfileSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": UserSerializer(user, context=serializer.data) }) serializers.py class CreateUserProfileSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('id', 'user',) extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create( validated_data['user'], validated_data['password']) user.save() return user error when sending a POST to the endpoint: File "/App/App_API/serializers.py", line 36, in create validated_data['password']) KeyError: 'password' Why that? If I do the following at my views code: print(request.data) I see the following at the console: <QueryDict: {'user': ['peter432'], 'password': ['OUBIfwiowef']}> Can somebody please share his way of creating a user. -
Why is setState callback state turning to "undefined" after populated with data?
I am trying to create a product with an image from browser. For the image field, I have a separate component to crop the image. // part of createProduct form. // this is a separete component. i passed callback to the set the image url <FileLoader onFileUpload={setImage}></FileLoader> <Form.Group controlId="brand"> <Form.Label>Brand</Form.Label> <Form.Control type="text" placeholder="Enter brand" value={brand} onChange={(e) => setBrand(e.target.value)} ></Form.Control> </Form.Group> My goal is to set the image, upload it first to Django, Django will return the url for S3 bucket, I will use that url to pass along with the createProduct form. inside FileLoader component, this is how I send the post request: const uploadFileHandler = async (image: File) => { const formData = new FormData(); formData.append("image", image); const config = { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${userInfo?.token}`, },}; return axios .post( `${process.env.DJANGO_API_URL!}/api/products/upload-image/`, formData, config ) // onFileUpload is callback to set the image in parent component .then((res) => onFileUpload(res.data)); }; This actually works. I get the url but as soon as I get it, it becomes undefined. What could be the reason? I also logged the "name" of the product and that state still persisted and also posted to the backend when I submit the form -
How to setup Django permissions to be specific to a certain model's instances?
Please consider a simple Django app containing a central model called Project. Other resources of this app are always tied to a specific Project. Exemplary code: class Project(models.Model): pass class Page(models.Model): project = models.ForeignKey(Project) I'd like to leverage Django's permission system to set granular permissions per existing project. In the example's case, a user should be able to have a view_page permission for one project instance, and don't have it for another instance. Is there a way to extend or replace Django's authorization system to achieve something like this? I could extend the user's Group model to include a link to Project and check both, the group's project and its permissions. But that's not elegant and doesn't allow for assigning permissions to single users. Would a project like django-guardian make sense here to gain object-level permissions? It feels like a quite bit of overhead for something that doesn't need that kind of granularity. -
Does save() function in Django overwrite older data in the DB table?
I am working on a Django app that works on two Databases, like so: Oracle DB(to fetch the data on an hourly basis) MySql DB (to save the processed data fetched from the Oracle DB) My Database config in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dashboard', 'USER': 'db1', 'PASSWORD': 'password1', 'HOST': 'localhost', 'PORT': '3306', }, 'MBDB': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'db2', 'PASSWORD': 'password2', 'HOST': 'localhost', 'PORT': '1521', } } My Django-Model: class Transactions(models.Model): class Meta: db_table='TRANSACTIONS' unique_together=(("TIME_UPDATED","TRAN_TYPE"),) indexes=[ models.Index(fields=["TIME_UPDATED","TRAN_TYPE"]), models.Index(fields=["TRAN_TYPE"]) ] TIME_UPDATED = models.DateTimeField() TRAN_TYPE = models.CharField(max_length=32,primary_key=True) SUCCESS = models.IntegerField() TECHNICAL_DECLINES = models.IntegerField() BUSINESS_DECLINES = models.IntegerField() TOTAL = models.IntegerField() PERCENTAGE_TECH_DEC = models.FloatField() def __str__(self): return self.TRAN_TYPE def save(self,D,tran): self.TIME_UPDATED=D self.TRAN_TYPE=T=tran['Type'] self.SUCCESS=S=int(tran['Success']) self.TECHNICAL_DECLINES=TD=int(tran['Tech_dec']) self.BUSINESS_DECLINES=BD=int(tran['Bus_dec']) self.TOTAL=total=S+TD+BD if total==0:#division by zero error constraint self.PERCENTAGE_TECH_DEC=0 else: self.PERCENTAGE_TECH_DEC=((TD/(total))*100) super(Transactions,self).save() Here the column ```TRAN_TYPE`` is defined as the primary key and both ```TRAN_TYPE``` AND ```TIME_UPDATED``` are composite primary keys as defined in ```Class Meta```. Sample-Queryset from views.py: {'SERVICE_CODE': 'IBKREVERSAL', 'Type': 'IBKREVERSAL', 'Success': 1, 'Tech_dec': 4, 'Bus_dec': 0} Queryset processed and saved @ Transactions on October 14, 2021 - 17:25:20: {'TIME_UPDATED': datetime.datetime(2021, 10, 14, 17, 25, 20, tzinfo=<UTC>), 'TRAN_TYPE': 'IBKREVERSAL', 'SUCCESS': 1, 'TECHNICAL_DECLINES': 4, 'BUSINESS_DECLINES': 0, 'TOTAL': 5, 'PERCENTAGE_TECH_DEC': Decimal('80.000')} Now when … -
Django BooleanField in Angular
I am building an App with Django as my backend and Angular as my frontend. In Django I have a BooleanField for my class "Employee". They can tick, if they are planning on being retired in 5 years or not: class Employee(models.Model): name = ... retired_5 = models.BooleanField(default = False) I have serialized my class and set up my REST API. class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('id', 'name', 'retired_5', ..., 'url') In Angular I build a form, that can create a new Employee. Without the Boolean field, it works: <mat-form-field> <mat-label>Name</mat-label> <input matInput [(ngModel)]="employee.name"> </mat-form-field> <button [mat-dialog-close]="employee" cdkFocusInitial> Add </button> But when I try to add the BooleanField, I am not able to add new employee: <section [(ngModel)]="employee.retired_5"> <mat-checkbox>Retired in the next five years</mat-checkbox> </section> Any idea on how to properly add BooleanField from Django and integrate into Angular? -
How to change status of the model in Django
I'm building a small to-do list project using Django, the to-do list has tasks divided into to-do, in-progress and done, I want to move to-do tasks from todo list to in- progress list, so I gave the to-do model 3 status, but I'm not sure how to set the status. Any help would be appreciated. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) details = models.TextField() def __str__(self): return self.status ''' views.py ''' def add_to_progress(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) Todo.objects.filter(id=todo_id).update(status='in_progress') context = {'form', form, 'todo', todo, 'project', project} return render(request, 'todo_lists/new_progress.html', context) def add_to_done(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) Todo.objects.filter(id=todo_id).update(status='done') context = {'form', form, 'todo', todo, 'project', project} return render(request, 'todo_lists/new_done.html', context) ''' -
How to access user information in utils.py in django (how to filter a model queryset)
I am trying to access the user information in utils.py, but don't know how. I need something like below(self.request.user) that was used for views.py: def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) user = self.request.user if user.is_student: queryset = Lead.objects.filter( status__exact="n" ) return context However, if you could help me solve a more fundamental problem of why I am trying to do this in the first place, it would be really helpful. You see, I am trying to run the view below in my django website: class CalendarView(LoginRequiredMixin, generic.ListView): model = Class template_name = 'leads/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context However, when I add the below code, it does not filter the model Class before rendering the calendar. Therefore, I end up going through all of the instances in the Class model. def get_queryset(self): return Class.objects.filter(date=datetime.date(1111,11,11)) Of course, I am going to edit the function above to use the … -
AttributeError: module 'tensorflow.python.training.experimental.mixed_precision' has no attribute '_register_wrapper_optimizer_cls' when deploying
I am getting the above error when trying to run a python django program on a windows server. The program works fine when I run it on my own laptop. The versions of keras and tensorflow and other libraries are as follows: absl-py==0.13.0 altgraph==0.17 argon2-cffi==20.1.0 asgiref==3.4.1 astunparse==1.6.3 async-generator==1.10 attrs==21.2.0 backcall==0.2.0 beautifulsoup4==4.9.3 bleach==4.0.0 bs4==0.0.1 cachetools==4.2.2 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 clang==5.0 click==8.0.1 colorama==0.4.4 cycler==0.10.0 Cython==0.29.23 dearpygui==0.8.64 debugpy==1.4.1 decorator==5.0.9 defusedxml==0.7.1 Django==3.2.7 django-rest-framework==0.1.0 djangorestframework==3.12.4 entrypoints==0.3 filelock==3.0.12 flatbuffers==1.12 future==0.18.2 gast==0.4.0 gensim==4.1.0 google-auth==1.32.1 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 graphviz==0.17 grpcio==1.40.0 h5py==3.1.0 huggingface-hub==0.0.12 idna==2.10 imbalanced-learn==0.8.0 ipykernel==6.0.3 ipython==7.25.0 ipython-genutils==0.2.0 ipywidgets==7.6.3 jedi==0.18.0 Jinja2==3.0.1 joblib==1.0.1 jsonschema==3.2.0 jupyter-client==6.1.12 jupyter-core==4.7.1 jupyterlab-pygments==0.1.2 jupyterlab-widgets==1.0.0 keras==2.6.0 keras-nightly==2.5.0.dev2021032900 Keras-Preprocessing==1.1.2 kiwisolver==1.3.1 libclang==11.1.0 Markdown==3.3.4 MarkupSafe==2.0.1 matplotlib==3.4.2 matplotlib-inline==0.1.2 mistune==0.8.4 nbclient==0.5.3 nbconvert==6.1.0 nbformat==5.1.3 nest-asyncio==1.5.1 nltk==3.6.2 notebook==6.4.1 numpy==1.19.5 oauthlib==3.1.1 opt-einsum==3.3.0 packaging==21.0 pandas==1.3.0 pandocfilters==1.4.3 parso==0.8.2 pefile==2021.9.3 pickleshare==0.7.5 Pillow==8.3.0 prometheus-client==0.11.0 prompt-toolkit==3.0.19 protobuf==3.17.3 py2exe==0.10.4.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.9.0 pyinstaller==4.5.1 pyinstaller-hooks-contrib==2021.3 pyparsing==2.4.7 pyrsistent==0.18.0 PySimpleGUI==4.47.0 python-dateutil==2.8.1 pytz==2021.1 pywin32==301 pywin32-ctypes==0.2.0 pywinpty==1.1.3 PyYAML==5.4.1 pyzmq==22.1.0 regex==2021.8.3 requests==2.25.1 requests-oauthlib==1.3.0 rsa==4.7.2 sacremoses==0.0.45 scikit-learn==0.24.2 scipy==1.7.0 seaborn==0.11.1 Send2Trash==1.7.1 six==1.15.0 smart-open==5.2.1 soupsieve==2.2.1 sqlparse==0.4.2 tb-nightly==2.7.0a20210914 tensorboard==2.6.0 tensorboard-data-server==0.6.1 tensorboard-plugin-wit==1.8.0 tensorflow==2.6.0 tensorflow-estimator==2.6.0 tensorflow-io-gcs-filesystem==0.21.0 termcolor==1.1.0 terminado==0.10.1 testpath==0.5.0 tf-estimator-nightly==2.7.0.dev2021091608 Theano==1.0.5 threadpoolctl==2.1.0 tokenizers==0.10.3 torch==1.9.0 tornado==6.1 tqdm==4.62.0 traitlets==5.0.5 transformers==4.9.1 typing-extensions==3.7.4.3 UNKNOWN==0.0.0 urllib3==1.26.6 waitress==2.0.0 wcwidth==0.2.5 webencodings==0.5.1 Werkzeug==2.0.1 widgetsnbextension==3.5.1 wordcloud==1.8.1 wrapt==1.12.1 yellowbrick==1.3.post1 I am not sure what the problem is since its running on my … -
AnonymousUser error on unauthenticated route Django
I am basically a FE developer. Recently I am trying to edit a Django project and remove authentication from an api. So after removing the authentication and trying to get the data without the token it shows an anonymous error. Works good for valid user django_1 | return method(value) django_1 | File "/app/deals/serializers.py", line 285, in get_already_liked django_1 | return usr.is_liking_deal(deal_obj=obj) django_1 | AttributeError: 'AnonymousUser' object has no attribute 'is_liking_deal' Here is the specific code in the serializers def get_already_liked(self, obj): usr = self.context["request"].user return usr.is_liking_deal(deal_obj=obj) After digging into the issue and researching I found out it is an issue with the model and primary key. as I am not sending an user through authentication Django is taking it as AnonymousUser and in the model AnonymousUser doesnt have any primary key.Here is the related code from the model (I think) class DealReactionManager(models.Manager): @staticmethod def is_user_liking_deal(user, deal): """Has user liked the deal already?""" try: DealReaction.objects.get(user=user, deal=deal) return True except DealReaction.DoesNotExist: return False class DealReaction(BaseModel): deal = models.ForeignKey(to="deals.Deal", related_name="reactions", on_delete=models.CASCADE) user = models.ForeignKey(to=get_user_model(), related_name="reactions", on_delete=models.CASCADE) objects = DealReactionManager() class Meta: unique_together = ("deal", "user") What I can understand from this is, after calling the deals api it looks for the liked deals … -
React's "npm run build" command gives error while running in "Virtual environment"
I'm trying to use react for front-end in Django project in a virtual environment. Steps I followed, Create a virtual environment Create a Django project in the same folder Create a react app in the same folder cd to react app Run "npm run build" I'm getting an error here saying, "'Export' is not recognized as the internal or external command" Log, ''' 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'build' 1 verbose cli ] 2 info using npm@6.14.15 3 info using node@v14.18.0 4 verbose run-script [ 'prebuild', 'build', 'postbuild' ] 5 info lifecycle frontend@0.1.0~prebuild: frontend@0.1.0 6 info lifecycle frontend@0.1.0~build: frontend@0.1.0 7 verbose lifecycle frontend@0.1.0~build: unsafe-perm in lifecycle true 8 verbose lifecycle frontend@0.1.0~build: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\code\PortfolioOct21\frontend\node_modules\.bin;D:\code\PortfolioOct21\venv\Scripts;C:\Program Files\AdoptOpenJDK\jdk-11.0.11.9-hotspot\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Python39\Scripts\;C:\Program Files\Python39\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\MinGW\bin;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\himan\AppData\Local\Microsoft\WindowsApps;C:\Chromedriver;C:\Program Files\Python39\Scripts;C:\Users\himan\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\himan\AppData\Roaming\Python\Python39\Scripts;C:\Program Files\heroku\bin;C:\Program Files\nodejs\;C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\bin;;C:\Users\himan\AppData\Roaming\npm 9 verbose lifecycle frontend@0.1.0~build: CWD: D:\code\PortfolioOct21\frontend 10 silly lifecycle frontend@0.1.0~build: Args: [ 10 silly lifecycle '/d /s /c', 10 silly lifecycle 'export NODE_ENV=production && rm -rf ./build && webpack --env.production --optimize-minimize' 10 silly lifecycle ] 11 silly lifecycle frontend@0.1.0~build: Returned: code: … -
Sorting (order_by) in list
I am building a BlogApp and I am trying to sort or order_by in list which contains multiple queries. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date = models.DateTimeField(auto_now_add=True) class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) body = models.CharField(max_length=30) date_added = models.DateTimeField(auto_now_add=True) views.py def mypage(request): query_1 = list(BlogPost.objects.filter(user=request.user).order_by('-date')) query_2 = list(Comment.objects.filter(user=request.user).order_by('date_added')) results = sorted(chain(query_1, query_2),key=attrgetter('date') , reverse=True) context = {'results':results} return render(reques, 'mypage.html', context) But is showing 'Comment' object has no attribute 'date' And I think this is because date field name is different in both model and i am querying with only one, But i have no idea how can I sort with different field name. Any help would be much Appreciated. Thank You -
How to get and match categories in a specific root of categories to be saved to the database?
Good day to all. You need to get all the id from the root category, and pass it to the creation of the model. At the moment I am doing it like this: game = driver.find_element_by_class_name('breadcrumbs').find_elements_by_tag_name('a')[0].text #root cat data_categories = driver.find_elements_by_class_name('rightDetailsBlock')[0].find_elements_by_tag_name('a') # I get categories that need to be mapped to the category root root_category = Category.objects.get(slug=game) #I get the root category children_categories = root_category.get_descendants(include_self=False) #I get children in the root category category_list = [] # list for saving to base for data_category in data_categories: data_category = data_category.text try: cildren_cat = children_categories.filter(slug__icontains=data_category) category_list.append(cildren_cat) except Exception as ex: print(ex) category_list.append(root_category) category_list = list(set(category_list)) When creating a model: try: data = Post.objects.get(title=title) print('File duplicated in database!') data.save() except Post.DoesNotExist: print('File starting save in database!') data = Post.objects.create( title=title, slug=slug, content=format_html(content), created_by_id=7, is_published=True, author=', '.join(map(str, author_list)), source=self.task.url ) data.category.add(*category_list) data.save() I am catching a mistake: Task modules.parser.tasks.parser_driver_task[da70b753-fd59-4103-a32d-806096b52616] raised unexpected: TypeError("Field 'id' expected a number but got <TreeQuerySet []>.") I understand what the mistake is. But I don’t know how to solve another problem in order to get the root category and match its child categories and get the list of id as a result? Thanks for the help. -
Javascript - how to display the list of items based on the user in the search box
I have a django web page where user can registered and below there is a table, which display the list of users from the database in the table. I have created a search box when user types the username, that particular username should reflect in the table.I'm trying this with Js script I'm not much proficient in js.I have tried but i couldn't able to get it. html: search: <input type="text" id="myInput" placeholder="Search by name" class="form-control ng-pristine ng-valid ng-touched" onkeyup="myFunction()"> table: <table class="table table-striped table-hover table-responsive-lg"> <thead> <tr> <th> <a class="text-nowrap" style="cursor: pointer;"> Username </a> <th> <a class="text-nowrap" style="cursor: pointer;"> Email </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Address<span aria-hidden="true" class="cil-arrow-top"></span> </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Phone </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Action</a> </th> </tr> </thead> {% for list in userb %} <tbody> <tr id="myUL"> <td id='tdusername'>{{list.username }}</td> <td id='tdemail'>{{list.email }} </td> <td id='tdmy_date'>{{list.address}}</td> <td id='tdtimezone'>{{list.phone}}</td> <td><a style="text-decoration:none" href="{% url 'app:home' list.slug %}" id="btn-link" class="btn btn-sm btn-secondary">Edit</a> </td> </tr> </tbody> </div> </div> {% endfor %} {% endif %} js part: <script> function myFunction() { input = document.getElementById("myInput"); ul = document.getElementById("myUL"); console.log(ul.textContent) li = ul.getElementsByTagName("td"); console.log(li.textContent) for (i = 0; i < li.length; i++) { a = … -
Send form and object in ajax
I'm trying to send a form an a javascript object in an ajax call like so: $("#formTabla").submit(function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ url : "{% url 'submit' %}", type: "POST", processData: false, contentType: false, data: { "checkboxes": formData, "datos": data } }); }); But all I'm getting as output is [object Object]. What am I doing wrong?