Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery registers task but beat is not scheduling tasks from installed apps
I'm having issues getting Celery/Celery Beat to schedule any tasks other than the ones in my celery.py file. I can see the tasks register with "celery inspect registered" but the tasks do not run on the schedule. I've read all of the docs and I'm a hitting a wall. Running Redis on Windows with Ubuntu WSL. Test- runs fine every 10 seconds and shows up in my shell PayClosedLines - is registered but doesn't come up in my shell when I run my celery worker. /proj/proj/celery.py from __future__ import absolute_import import os from celery import Celery from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()]) @app.task(bind=True) def debug_task(self): print('Request: [0!r}'.format(self.request)) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, test.s('test'), name='add every 10') sender.add_periodic_task(10.0, ) sender.add_periodic_task(30.0, test.s(), expires=10) @app.task def test(arg): print(arg) ''' proj/proj/settings.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' from datetime import timedelta CELERY_BEAT_SCHEDULE = { 'Payout bets every 10 seconds': { 'task': 'UFCBetting.tasks.PayClosedLines', 'schedule': timedelta(seconds=10.0), }, } CELERY_IMPORTS = ('UFCBetting.tasks',) proj/app/task.py from __future__ import absolute_import, unicode_literals from .MyBookieTools import get_odds from .models import BettingLines, Bets, CustomUser from celery import task, shared_task @task(name='UpdateLinesTable') def … -
How to pass slug to UpdateView?
I am trying to get a slug field to be passed accessing an UpdateView but when I click the button it does not redirect or do anything for that matter. I am used to using a <int:pk> while handling UpdateViews but in this scenario I am using an open source app which uses a slug field for it's URL. URL: url(r'^(?P<slug>[\w-]+)/update/$', view=QuizUpdateView.as_view(), name='quiz_update'), Model attribute and method: url = models.SlugField( max_length=60, blank=False ) def get_absolute_url(self): return reverse('quiz_detail', kwargs={'pk': self.pk, 'slug': self.url}) Template: <button class="btn btn-default btn-sm" onclick="location.href='{% url 'quiz_update' slug=quiz.url %}">Update Test</button> -
How to load fixture right way when deploy?
I have a problem with load fixture file when deploy django. More detail: I have many fixture files to be needed load to database, so I have 2 ways to deal with it: Load fixture during migrate operation Pros: Less time and can load specific file Cons: Can't apply for local developer because model in fixture file may be change in future (maybe show error "missing column", etc.) Load fixture when deploy Pros: Can apply for local developer Cons: Due to have many fixture files so time to load fixture during deploy too much (can't tracking fixture file have been loaded) Do you have anyway to handle fixture file? -
django checked if the checkbox is true
<input type="checkbox" value="1" name="Asthma" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student have Asthma"> <input type="checkbox" value="1" name="Congenital" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student have Congenital Anomalies"> <input type="checkbox" value="1" name="Contact" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student use Contact lens"> i have this code in my html <script type="text/javascript"> $('#checkbox-value').text($('#checkbox1').val()); $("#checkbox1").on('change', function() { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } $('#checkbox-value').text($('#checkbox1').val()); }); </script> my problem is everytime i save into my database the result always true? even i unchecked the checkbox. i dont know if i am doing right in my javascript this is my views.py Asthma = request.POST['Asthma'] Congenital = request.POST['Congenital'] Contact = request.POST['Contact'] V_insert_data = StudentUserMedicalRecord( Asthma=Asthma, CongenitalAnomalies=Congenital, ContactLenses=Contact ) V_insert_data.save() -
Django Filter Course Titles By Searching
I want to filter course titles by searching for them. The code is properly adding this to the browser's URL (example typing in Django into the search box): ?title_contains=Django&view_count_min=&view_count_max=&date_min=&date_max=&category=Choose... However, when clicking the search button, the courses in the for loop do not filter down based on what was typed into the search box. I think it has to do with the context variable in the views.py filter function. How do I fix it to get my search to work? Live example: http://bb5bbf00.ngrok.io/courses/ views.py: def filter(request): qs = Course.objects.all() title_contains_query = request.GET.get('title_contains') if title_contains_query != '' and title_contains_query is not None: qs = qs.filter(title__icontains=title_contains_query) context = { 'queryset': qs } return render(request, "course_list.html", {}) class CourseListView(ListView): model = Course models.py: class Subject(models.Model): SUBJECT_CHOICES = () name = models.CharField(max_length=20,choices=SUBJECT_CHOICES) def __str__(self): return self.name class Course(models.Model): SKILL_LEVEL_CHOICES = ( ('Beginner', 'Beginner'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced'), ) slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() allowed_memberships = models.ManyToManyField(Membership) created_at = models.DateTimeField(auto_now_add=True) subjects = models.ManyToManyField(Subject) skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True) visited_times = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:detail', kwargs={'slug': self.slug}) @property def lessons(self): return self.lesson_set.all().order_by('position') course_list.html: <form method="GET" action="."> <div class="form-row"> <div class="form-group "> <div class="input-group"> <!--Search box to search for … -
Is it possible to start virtual environment via file with bash commands?
Almost every day I have to start my django project. So the sequence of commands that are used: cd myProject source venv/bin/activate cd djangoproject python3 manage.py runserver I have put these commands to start.txt file. But bash start.txt doesn't start virtualenv. Am i doing something wrong? -
How to make users rate themselves in Django?
It's been a few days since I've been trying to create a part of a system I'm making, but I haven't been successful. I would like to have a guideline to get users to rate themselves (5-star rating) and make each user's grades in the database so I can manipulate them later. I am extending the AbstractUser class to add new information, another to evaluate with my user as fk, but I can't think more than that. If anyone can help me, I appreciate! -
How to prevent being able to access a field of a QuerySet object if the field was not in provided Django's only() method?
Let's pretend I have this Django model: class Person(models.Model) name = models.CharField() age = models.IntegerField() Then I do this query on the model: queryset = Person.objects.filter(name="Joe").only("name") # Notice that I want to only select the name field. object_list = list(queryset) # Purposefully triggered the database hit by calling list on it. How do I prevent being able to do this?: object_list[0].age # Accessing a field that I did not include in the "only" method triggers an additional hit to the database. I would like it to raise an Exception or just do nothing instead of hitting the database for the second time. -
Is there another effective method to create a chatbot skeleton to analyze inputs?
I am trying to create a chatbot using Django/Channels WebSockets, however, I am having problems with the communication. Once the user send the message I require to analyze it and use some nlp or nltk python libraries to extract the intent. I try to use the essence of a chatroom but the program it is not printing the information i want. Does anyone knows another approach to build or create chatbot and be able to add my python code? Thank you so much for your attention.enter image description here -
Implementing a device code to create a new device session
I'm looking to implement a setup were my logged in user (Admin) can Add a device to an authorized devices list and then that device ipad, android tablet, etc. can log into a limited functionality dashboard via a simple say 6 digit device code. I would prefer that once the device activates that device code the session persists until the session gets manually terminated. I have an idea on how I would tackle this but I would like input for terms of security and design flaws. Thank you in advance! -
How could I make the Edit button work from a modal?
How could I make my edit button work from modal to make and update to the database. My Modal: (body only) <div class="modal-body"> <form class="form" id="employee_update" method="post" action=""> <div class="row"> <div class="col-md-6"> <label>First Name</label> </div> <div class="col-md-6"> <input class="text" type="text" id="first_name" placeholder="{{employee.first_name}}"> </div> </div> <div class="row"> <div class="col-md-6"> <label>Middle Name</label> </div> <div class="col-md-6"> <input class="text" type="text" id="Middle_name" placeholder="{{employee.middle_name}}"> </div> </div> <div class="row"> <div class="col-md-6"> <label>Last Name</label> </div> <div class="col-md-6"> <input class="text" type="text" id="last_name" placeholder="{{employee.last_name}}"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" id="emp_update" class="btn btn-primary" style="background-color: green">Edit</button> </div> </div> JS(Tried but it wont work) <script> $("#emp_update").click( function() { $('#employee_update').submit(); }); </script> For now after this is my views.py since im still working on that button. def employee_update(request): return redirect(request, 'index.html') -
django website served by nginx can not be visited from outside properly
I used Django + nginx + uWSGI to deploy a website to example.com (this is also the hostname of my instance where I put the Django app on Google Cloud Platform) following the instructions here https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html. Now here's the strange thing. I found that all devices under my university's WiFi can access my website (http://example.com) but devices outside my network (for example, in another city) cannot access it. Does anyone know what is going on here? Thank you very much in advance. -
ModuleNotFoundError: No module named 'djangofeeds'
I have followed the sample code given in the task-cookbook Ensuring a task is only executed one at a time That code uses from djangofeeds.models import Feed I do not know where to get the djangofeeds module from? -
Excluding a ForeignField from Tastypie API
I have this resource: class DataResource (ModelResource): related_id = fields.ManyToManyField(RelatedResource, attribute=‘related_id', null=True, full=True) class Meta: query-set = Data.objects.all() resource_name = 'data' authorization = Authorization() filtering = { ‘related_id' : 'exact', } excludes = [ ‘related_id' ] which I need it to allow filtering on related_id which is a foreign key. That part works well. I then want to exclude related_id from the result, but the excludes here has no effect on that foreign field. The reason why I want to exclude it is that Data object is related to 1000s of Related - so every time you pull one Data, it also pulls all the Related. This becomes heavy to load with many requests. -
Export CSV huge queryset - Django rest framework
I'm trying to realize an endpoint to export a CSV file containing information about users. The thing is our database contains more than 250,000 users. So right now, that's what I'm doing. I create a CSV file on my server and then write in it. for idx, user in enumerate(queryset): print('{}/{}'.format(idx+1, total)) row = [user.first_name, user.last_name, user.email] # some logic # ..... csv_writer.writerow(row) Once the loop is over I send the file: file = open('export_users.csv', 'rb') response = FileResponse(file, content_type='text/csv') response['Content-Length'] = os.fstat(file.fileno()).st_size response['Content-Disposition'] = 'attachment; filename="%s"' % '{}_export_users.csv'.format(date_now.strftime('%Y-%m-%d:%M:%S')) return response But I have a huge problem with this method. It takes too much time and I got timeout by Cloudflare or my own server. So my questions are: Is there a faster method to loop over my 250,000 users? Should I change my way to create my csv file? Thank you in advance! -
Django view not rendering correctly after view execution via template
I have this template: folder.html. I have a button on it that calls a view called calculate_folder. This view makes some calculations and then renders back to folder.html. The problem is that when it renders, the view calculations are made, but the link in the browser is still the same (localhost:8000/calculate_folder/pk). Here is some sample code to showcase the issue: @user_passes_test(lambda u: u.is_superuser) def calculate_folder(request, pk): folder = get_object_or_404(Folder, id=pk) folder.status = 'P' folder.save() context = { 'folder': Folder.objects.get(id=pk) } return render(request, 'dashboard/folder.html', context) Here is the urls.py content: path('calculate_folder/<pk>', views.calculate_folder, name='calculate_folder'), And here is the template itself: <div class="inner"><a href="/calculate_folder/{{folder.pk}}"><input type="submit" style="width: 10em;" class="profile-edit-btn btn-info mb-2" name="btnAddMore" value="Calculate"/></a></div> I want to click on the button, go to the url, execute the view, but go back to the initial page. -
posted form not properly arriving in generic class based view
I am at a loss for what the solution could be to this problem. It is essentially quite simple. I want to update the database with the form in this ProductCreateView class as a result of the user filling it in and submitting on my website. The form is displayed properly and the user is able to submit the data after which I see in the console that the POST request was made successfully. However, after that, nothing happens to this post data and the user is redirected to the front page. It seems like the POST data is going nowhere. Both of the functions of form_valid and form_unvalid don't print anything and the database is not updated. views.py class ProductCreateView(CreateView): model = added_product fields = ['product_name', 'product_price', 'product_url_end'] def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. print("Valid form!") return HttpResponse('Hello') def form_invalid(self, form): print("invalid form!") # This method is called when invalid form data has been POSTed. return HttpResponse('Hello') models.py class added_product(models.Model): product_name = models.CharField(max_length=200) product_price = models.CharField(max_length=200) product_url_end = models.CharField(max_length=500) def get_absolute_url(self): return reverse('product-create') added_product_form.html <form action="/bolcombot/" method="post"> {% csrf_token %} {{ form }} <input … -
Getting an 'str' object has no attribute '_max_attempts' error for cloud firestore transaction in python
Please anyone can resolve this error is much appreciated. Im using firebase_adminsdk and want to update the status of an order from my django project. import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate(settings.FIREBASE_CONFIG_PATH) firebase_admin.initialize_app(cred) dbFire = firestore.client() @firestore.transactional def updateFirestore(docId, status, assignedTo, profileURL): fireTransaction = firestore.client.transaction() docRef = dbFire.collection(u'orders').document(settings.ORDERS_CONFIG).collection(u'orders').document(docId) snapshot = docRef.get(transaction=fireTransaction) data = { "status":status, "status_code":orderStatuses[status], "assignedTo":assignedTo, "profileURL":profileURL, "dateupdated": datetime.datetime.now() } try: # docRef.update(data) res = fireTransaction.update(docRef, data); print('Transaction result: ', res) return True except firebase_admin.exceptions.FirebaseError as fe: logger.error(msg='Firebase error: updateFirestore: {}. Order details: {}, {}'.format(fe, docId, data)) return False except Exception as e: logger.error(msg='Unknown error: updateFirestore: {}. Order details: {}, {}'.format(e, docId, data)) return False I am getting the below error always. Tried many ways. But could not solve this. 'str' object has no attribute '_max_attempts' -
Django ImageField not uploading files to media folder nothing helps
I was seen all themes and tutorials and docs that i found, but i don't solved my problem. ImageField upload_to don't upload files to media folder. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py image = models.ImageField(blank=True, upload_to = "images/") File loading from form is correct. In template on {{ object.image.url }} i see path media/name.png Database field showing name of file: name.png But file name.png NOT EXISTS in folder media. Folder media was created. -
Can a user submit text to refine a filter with Django-filter?
I have a search that uses Django-filter. The search uses a geographic location, but I think my question would be applicable to any kind of Django-filter search. The filter gets the geographic location of a click on a Leaflet map, then searches within a given distance of that point. Right now, that search radius is fixed, but I would like for users to enter a custom search radius. Is there a way to add a field to the filter set and retrieve the value entered there? Here's the filter that works: #filters.py def spatial_search(self, queryset, name, value): lat = float(value.split(',')[0]) lng = float(value.split(',')[1]) point = GEOSGeometry('POINT(%f %f)' % (float(lng), lat)) search_results = queryset.filter(image__location__distance_lt=(point, D(km=5))) return search_results The model field that's being searched is location in the model image. The part I would like to be variable is D(km=5), so it would be something like D(km=<user-input>). I can't find anything in the documentation about adding a text-input field, so I figured I'd ask before trying to write some complex javascript/html thing. -
Exporting CSV from Django/Graphql
I need to generate and output a csv file/data from my db data to my frontend. I found this and followed the instructions: https://docs.djangoproject.com/en/2.2/howto/outputting-csv/ However, I am using graphql and graphene. The instructions above don't say in what format the output should be returned. When I return plain String, all I get returned is "<HttpResponse status_code=200, \"text/csv\">". Example of code: class Query: users_csv = graphene.String() ... @classmethod @login_required def resolve_users_csv(cls, obj, info): response = HttpResponse(content_type="text/csv") writer = csv.writer(response) header = [ "EmployeeEmail", "TeamMemberName", "PhoneNumber", "MobileNumber", "IsAdmin", ] content = [] for u in User.objects.filter(customer=info.context.user.customer): content.append( [ str(u.email) if u.email else "", str(u.get_full_name()), str(u.phone_number) if u.phone_number else "", str(u.mobile_number) if u.mobile_number else "", str(u.is_admin), ] ) writer.writerow(header) writer.writerows(content) return response Any help or pointers is very appreciated... -
How can I check these messages in my Flower "broker" tab?
I have been doing some observations on my Flower dashboard for my instance. I see that there is a large amount of messages in my broker tab. Does anyone know how I can check these messages? Do they mean anything significant? -
How to authenticate user via REST using email and password with Django Rest Framework
I have a very simple desire: to authenticate (log in) user over REST. I need to use email and password. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'rest_framework', 'modeltranslation', 'smoothapps', 'corsheaders', 'django_s3_storage', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account' ] 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) urls.py: re_path(r'^rest-auth/', include('rest_auth.urls')), When I do: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"email": "admin@test.com", "password": "zyzzyx' \ http://localhost:8000/rest-auth/login/ The error message is: Unable to log in with provided credentials. -
How to filter by list of values in Django admin?
How can I filter the objects in Django Admin by list of values entered by user in a text field? For example - a user would input a list of IDs separated by commas and the Django Admin should return all the objects that match those IDs? -
count the number of likes from another model Django
implementing a like model where user could like a pet. If user presses like, isLike would be true while unlike would be isLike is false Model class pet(models.Model): name = models.CharField(max_length=50) class likes(models.Model): petId = models.ForeignKey( "pet", on_delete=models.CASCADE, null=True) liker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) isLike = models.BooleanField(default=False) class countlikes(models.Model): petId = models.ForeignKey( "pet", on_delete=models.CASCADE, null=True) numOfLikes = models.PositiveSmallIntegerField(default=0) Serializer class PetSerializer( serializers.ModelSerializer): class Meta: model = pet fields = '__all__' class LikesSerializer( serializers.ModelSerializer): class Meta: model = likes fields = '__all__' class CountlikesSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = countlikes fields = '__all__' what I tried: two get requests to get the Number of likes and if isLike is true or false. If user likes, i would increment the numOfLikes and decrement if user unlikes and then do a put request.