Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How are my html templates able to get the username without any arguments passed by views.py?
I have a djongo engine based google authentication applications My views.py renders the homepage, without passing any arguments: return render(request=request,template_name="mainapp/homepage.html") And homepage.html looks like: <html> <head></head> <body bgcolor = "green"> <p>THIS IS THE HOMEPAGE</p> {% if user.is_authenticated %} <p class="display-4">Hello, {{ user.username }} you are signed in</p> <a href="/account/logout">Log out</a> {% else %} <a href={% url "social:begin" "google-oauth2" %}>Login with Google</a> <p>Not signed in</p> {% endif %} </body> </html> Yet after the user logs in it shows the correct username( not that of the admin). -
How to call function if http request is POST in Django views and pass new submitted file name to function call?
I'm working on web application in which user upload a video and we perform speech recognition on it and then translate its text in another language.So, if the request is POST then we call that function which perform these functionalities and if request is GET it should not call that but in my case,on POST request, function execute first and then POST request is submitted.And it perform functionality on the last video in database. It gives the same result even if I put function call at the end of POST request condition statement and if I put function call out of POST request condition the function call on every reload of page which is not required and I don't know other ways how to solve this problem. """ Django==2.0.2 views.py""" def generatingsubtitle(request): latestvideo = Video.objects.last() videofile = latestvideo.videofile path = settings.MEDIA_ROOT + videofile.name filename = os.path.splitext(videofile.name)[0] srtpath=settings.STATIC_ROOT+filename if request.method == 'POST': #function call main(path, srtpath) form = forms.VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('generatingsubtitle'), ) else: form = VideoForm() return render(request, 'app/generate.html', { 'form': form, 'videofile': videofile, 'filename':filename, }, ) I expect that ,POST request is submitted first and we take path of newly submitted file … -
How to fix "object() takes no parameters" error in Django
I am trying to access my database called Active_Project_View. Inside of this is the information I am trying to display in ag-grid. I have used the objects.all() to get the information out but it's not work. class getActiveGrid(): def get_queryset(self, request, format=None): queryset = Active_Project_View.objects.all() return queryset def get(self, request, format=None): filters = request.data serializer = ActiveGridViewSerializer(self.get_queryset(filters), many=True) return HttpResponse(serializer.data) <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="static\app\content\agGrid.css" > <script src="https://unpkg.com/ag-grid-community/dist/ag-grid- community.min.noStyle.js"></script> <link rel="stylesheet" href="https://unpkg.com/ag-grid- community/dist/styles/ag-grid.css"> <link rel="stylesheet" href="https://unpkg.com/ag-grid- community/dist/styles/ag-theme-balham.css"> </head> <body> <h1>Project Grids</h1> <div class="box c"> Active Projects <script type="text/javascript" charset="utf-8"> const Active_Project = [ { headerName: "Last Name", field: "app.Customer_Last_Name", sort: 'asc' }, { headerName: "First Name", field: "Customer_First_Name", }, { headerName: "Phone Number", field: "Customer_Phone_Number", }, { headerName: 'Employee', field: 'Employee_First_Name' }, { headerName: 'Zip Code', field: 'Customer_Zip' }, ]; const ActiveProjectGrid = { columnDefs: Active_Project, }; var eGridDiv1 = document.querySelector('#ActiveProjectGrid'); new agGrid.Grid(eGridDiv1, ActiveProjectGrid); fetch('getActiveGrid').then(function (response) { return response.data(); }).then(function (data) { ActiveProjectGrid.api.setRowData(data); }) </script> </body> </html> url(r'^getActiveGrid$',app.views.getActiveGrid, name='postActive'), class ActiveGridViewSerializer(): class Meta: model = Active_Project_View fields= '__all__' class Active_Project_View(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Customer_First_Name= models.CharField(max_length=255, blank = False) Customer_Last_Name = models.CharField(max_length=255, blank = False) Customer_Phone_Number = models.CharField(max_length=10, blank=True) Customer_Zip = models.CharField(max_length = 5, blank … -
django left outer join filter non-matching records
The goal is to find out if a Survey Response doesn't have current answers for all top level questions. This could be done by getting all top level questions for the Response, and then filter out the questions which don't have current answers. I can write this in SQL but is there a way I can implement this using django's QuerySet interface? Models class Survey(Model): ... class SurveySection(Model): survey = ForeignKey(Survey, related_name='survey_sections') class SurveyQuestion(Model): survey_section = ForeignKey(SurveyQuestion, related_name='survey_questions') parent = ForeignKey('self') #questions can be nested class SurveyResponse(Model): survey = ForeignKey(Survey, related_name='survey_responses') class SurveyAnswer(Model): survey_response = ForeignKey(SurveyResponse, related_name='survey_answers') survey_question = ForeignKey(SurveyQuestion, related_name='survey_answer') SQL This should find all the top-level questions for the Survey the Response is for, getting the current answers that match those questions and removing the questions that don't have answers. select * from survey_surveyquestion question join survey_surveysection section on section.id = question.survey_section_id join survey_survey survey on survey.id = section.survey_id join survey_surveyresponse response on response.survey_id = survey.id left outer join survey_surveyanswer answer on answer.survey_question_id = question.id and answer.is_current = true where response.id = 16 and answer.id is null and question.parent is null -
Is there any way to retrieve Objects from ManyToManyFields in the order they were added?
I have a bunch of Recipes and would like the User to have the option to save the ones he likes. I originally made it with a ManyToManyField on the Recipe model to to the User model but the problem was i wasn't getting them back in order that they were saved. Is there any way to do this? If not, what should i do instead to be able to keep the order? Make a third model with a date field and link the two? Seems like a bit of a waste. Any help would be nice. Thank you -
could not pass custom response
when I am querying for the job_seeker profile and If there is no job_seeker data then I was getting an error JobSeeker models query does not exist. I instead want to pass empty list if there is no data. For this, i tried the following way but i am getting an error so could not pass the custom response class JobSeekerNode(DjangoObjectType): class Meta: model = models.JobSeeker interfaces = (relay.Node, ) class JobSeekerQueries(ObjectType): job_seeker = Field(JobSeekerNode) def resolve_job_seeker(self, info, **kwargs): data = {} if info.context.user.is_authenticated: try: profile = Profile.objects.get(user=info.context.user) try: job_seeker = models.JobSeeker.objects.get(profile=profile) data['job_seeker'] = job_seeker except: # when there's no row instead of passing error, pass empty list data['job_seeker'] = [] return JsonResponse(data) except Profile.DoesNotExist: return [] return None this is the error i get when trying to pass the custom response(empty list if there's no data) { "errors": [ { "message": "Received incompatible instance \"<JsonResponse status_code=200, \"application/json\">\"." } ], "data": { "job_seeker": null } } -
Image upload in CreateView
I have a CreateView in my project to post a tweet-like-post. It has a title and content. It look like this in views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): # Author for post (required- if no- error) form.instance.author = self.request.user return super().form_valid(form) And I would like to add picture-upload column to make a persons able to upload a picture with the post. My models.py looks like this class Post(models.Model): title = models.CharField(max_length=100, verbose_name='タイトル') content = models.TextField(verbose_name='内容') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('Post-detail', kwargs={'pk': self.pk}) I already have a uploaded_pic folder in my static with 777 permision. Could you please tell me how to add there working picture-upload column -
Cannot access the Django server at http://127.0.0.1:8000/ after creating superuser
At the first time, it worked totally fine (impassion) Subinui-MacBook-Pro:3rd subin$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 20, 2019 - 01:42:24 Django version 2.2.2, using settings 'impassion_community.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [20/Jun/2019 01:42:50] "GET /admin HTTP/1.1" 301 0 [20/Jun/2019 01:42:50] "GET /admin/ HTTP/1.1" 302 0 [20/Jun/2019 01:42:50] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1819 [20/Jun/2019 01:42:50] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [20/Jun/2019 01:42:50] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17944 [20/Jun/2019 01:42:50] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [20/Jun/2019 01:42:50] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [20/Jun/2019 01:42:50] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [20/Jun/2019 01:42:50] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 Not Found: /favicon.ico [20/Jun/2019 01:42:50] "GET /favicon.ico HTTP/1.1" 404 1985 ^C(impassion) after it, I created the superuser Subinui-MacBook-Pro:3rd subin$ python3 manage.py createsuperuser Username (leave blank to use 'subin'): tnqls7378 Email address: tnqls7378@gmail.com Password: Password (again): Superuser created successfully. and tried to login, so I opened the chrome and connect to http://127.0.0.1:8000/admin/ again, but now I see the error message that I can't connect to the server anymore. what could possibly wrong? -
arcpy in django doesnot run
I have a script with ArcGIS using arcpy model. And I want to combine it with Django. The script runs on console successfully, however, when running with Django, I find the arcpy functions do not run. So I make a simple test for it, and get the same result. test.py import arcpy import os def test_arcpy(): tempFolder = arcpy.env.scratchFolder tempGDBPath = os.path.join(tempFolder, 'test.gdb') arcpy.env.overwriteOutput = True if not arcpy.Exists(tempGDBPath): arcpy.AddMessage('create..') arcpy.CreateFileGDB_management(tempFolder, 'test.gdb') return arcpy.Exists(tempGDBPath) views.py from django.http import HttpResponse from . import test def t(request): msg = str(test_arcpy()) return HttpResponse(msg) If I run the test.py in console, it return True.But if I run it in django, it always return false. If I cannot solve it , I cannot make more difficult script in django. Can you help me? I found the similar question in Flask app with ArcGIS, Arcpy does not run, but no solution in this question. -
How to upload docker django app to my vps
I am new in Django and docker and I finished my first docker's app with poqtgresql recently. Now I have a VPS with linux cent os. Please give me a source for full structure of how to Upload my app to my VPS.(I have no experience in server, so it can be great give me some info for configuration of server) -
How to fix 'No module named 'whitenoise'?
Django Version: 2.2.2 Exception Type: ModuleNotFoundError Exception Value: No module named 'whitenoise' Exception Location: in _find_and_load_unlocked, line 965 I from the local computer, put the project on a hosting, and such error got out '''''' CSS static doesn't work -
Function based view over CBV in django
I am very new to django. I am trying to learn django but i got confused which method i can choose between class-based views and function-based views.I personally find function-based views more easy than class-based views.Can i do it with only function-based views or class-based views is also very compulsory, so i can focus on the one more while moving forward to django. \ -
Get current item in Django list or template view
I’m trying to make a like button in Django . But in order for me to add the like , I will need to get the current item . I don’t won’t to have to go the the items detail view to get the current item , is there anyway I can get the current item in a list view. ? -
how to display web service data from a website and show it in HTML using Python?
I can't show this data in a table using Python, I just want to show this web service data in a table in an HTML file using Python. This is the web service data that I am trying to output into a table for viewing: {"returnCode":0,"message":null,"resultList":[{"poNo":"0000123456","deliveryDock":"D1","dcNo":"DC01","vendorNo":"0001112222","orderDate":"2019-06-07","deliveryDate":"2019-06-02","deliveryTime":"00:00","noOfPallets":"10.0000","source":"MANUAL","status":"Scheduled","auditList":[{"oldDeliveryDock":"D2","oldDeliveryDate":"2019-06-03","oldDeliveryTime":"01:30","changedBy":"XASNH","changedOn":"2019-06-07","reasonCode":"FCST"},{"oldDeliveryDock":"D3","oldDeliveryDate":"2019-06-04","oldDeliveryTime":"03:30","changedBy":"XRCA4","changedOn":"2019-06-07","reasonCode":"WOW"}]}]} I did a request like this in my views.py python page, but I am not sure how I would show this request in an HTML page def index(request): url = """http://53.01.187.244/Booking/getbookInfo?poNo=0000123456""" r = requests.get(url) data_dfs = pd.read_json(r.text) return render(request, 'users/index.html', {'data_dfs': data_dfs}) -
views.py and urls.py do not connect to perform a function
I have a mysql database connected to django, I know it is connected because you already showed me data. However I made a small form to do tests and does not save the data. The code is correct because I already moved it from place to def index (request): and there if you send me the data what is not because it does not enter correctly in the function that I did views.py from django.shortcuts import render, redirect from models import Test def index(request): test = Test.objects.all() context = {'test': test } return render(request, 'test_app/index.html', context) def create(request): print request.POST test = Test(name=request.POST['name'], breed= request.POST['breed']) test.save() return redirect('/') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^create/$', views.create) ] index.html <form action"/create" method="post"> {% csrf_token %} <label for="name">Name: <input type="text" name="name" /> </label> <label for="breed">Breed: <input type="text" name="breed"/> </label> <input type="submit" value="create" /> </form> I do not have an error just do not save in the database, in the console if you send a POST but without any variable. Use python 2.7 and django 1.1 -
Django model.field validators don't execute for required Boolean fields
My use case: I have a Yes/No question the user must answer, but they may answer it yes or no. I don't want to supply a default because I need the user to actively select their answer. If they do not select an answer, I want a form validation error, like "This field is required". I know that could store this in the DB as a CharField, but I'd prefer to store it as a required BooleanField. The issue appears to be that the form validation logic does NOT enforce required=True for Boolean fields, nor does it call the model field's custom validators when a value of '' is returned in the POST data. My setup: boolean_choices = ( (True, 'Yes'), (False, 'No'), ) def boolean_validator(value): if value is not True and value is not False: raise ValidationError("This field is required.") class Item(models.Model): accept = models.BooleanField( choices=boolean_choices, validators=[boolean_validator] ) class ItemForm(ModelForm): class Meta: model = Item fields = ['accept'] A complete, working demo of the issue is here: https://repl.it/@powderflask/django-model-form-validators Reproducing the issue create or edit an item, and set the 'accept' value to None ("-------") --> save will crash - notice form.is_valid() passed, crash is in form.save() --> notice that … -
Swal.fire opens unclicable modal (behind html body)
I'm currently having the following issue with Sweet Alerts 2: The modal is loaded, but it doesn't seems to be clickable I've investigated over the console and found two important things: first, it happens even if I run Swal.fire({}) on chrome console this behaviour is kept. I've tried to replace some codes on the source code, with no luck. Z-index seems to have no effect on this, and the target object that loads the div is not trivial. I'm doing this work on django, but the problem is not there so i'll ommit the django code. My html code on _base.html is: {% block styles %} <link href="{% static 'system/css/bootstrap.min.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/material-dashboard.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/sweetalert2.css' %}" rel="stylesheet"/> <link href="{% static 'system/css/jquery.datetimepicker.min.css' %}" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link crossorigin="anonymous" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" rel="stylesheet"> {% endblock %} {% block html5shim %} <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script> {% endblock %} {% block extra_scripts %} {% endblock %} {% block extra_head_base %} <script defer src="https://use.fontawesome.com/releases/v5.0.4/js/all.js"></script> <script src="{% static 'charts/code/highcharts.js' %}"></script> <script src="{% static 'charts/code/modules/exporting.js' %}"></script> <script src="{% static 'charts/code/modules/export-data.js' %}"></script> <script src="{% static 'system/js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'system/js/sweetalert2.js' %}"></script> {% block extra_head %}{% … -
Django FilterSet with distinct AND order_by
I want to use django-filter to create a FilerSet with distinct results for field A, ordered by field B (in another model). Database is PostgreSQL. Commented lines in class MinutesListView are things I've tried (in various configurations). models.py class Case(models.Model): case_filed_date = models.DateField() case_number = models.CharField(max_length=25, unique=True) as_of_timestamp = models.DateTimeField() def __str__(self): return self.case_number class Minutes(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) minute_entry_text = models.TextField(blank=True, null=True) minute_entry_date = models.DateField(blank=True, null=True) minute_entry_type_text = models.CharField(max_length=255, blank=True, null=True) filters.py class MinuteFilterSet(df.FilterSet): case__case_number = df.CharFilter(lookup_expr='icontains', label='Case Number', distinct=True) minute_entry_text = df.CharFilter(lookup_expr='icontains', label='Minutes Text') class Meta: model = Minutes fields = ['minute_entry_text'] order_by = ['-case__case_filed_date'] views.py: class FilteredListView(ListView): filterset_class = None def get_queryset(self): # Get the queryset however you usually would. For example: queryset = super().get_queryset() # Then use the query parameters and the queryset to # instantiate a filterset and save it as an attribute # on the view instance for later. self.filterset = self.filterset_class(self.request.GET, queryset=queryset) # Return the filtered queryset return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Pass the filterset to the template - it provides the form. context['filterset'] = self.filterset return context class MinutesListView(FilteredListView): filterset_class = filters.MinuteFilterSet paginate_by = 25 # ordering = '-case__case_filed_date' # queryset = Minutes.objects.all() queryset = Minutes.objects.distinct('case') The … -
Django Rest Framework: User Not Updating with UpdateModelMixin
Using django-rest-framework and django-rest-auth, I have the following test case to ensure that a custom user's profile can be partially updated: def test_update_user_profile_first_name(self): client = APIClient() client.login(email=self.test_email, password=self.test_password) data = {"first_name": self.first_name} response = self.client.put("/users/" + self.user_id, data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(self.test_user.first_name, self.first_name) client.logout() However, this test fails with test_user's first name still not updating. What mistake am I making here? Relevant files: # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') # views.py class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer With my URLs following this pattern: users: { list() read(id) update(id, username, email, [first_name], [last_name]) partial_update(id, [username], [email], [first_name], [last_name]) delete(id) } -
How to Dynamically Compute Value in View and Display in Template (Django)
I want to dynamically pull values from two user input fields, a textbox and a dropdown, and then send those values to my view to calculate a new value and display said value in my template. This seems like a fairly simple scenario, but I am new to Django/Python. Any help is greatly appreciated! views.py def presales(request): my_opportunities = cwObj.get_opportunities() context = {'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) def presales_total(request): hours = request.GET.get('hours') engineer_level = request.GET.get('selected_engineer_level') if engineer_level == 'PM': wage = 225 elif engineer_level == 'Solutions Technician': wage = 175 elif engineer_level == 'Solutions Engineer': wage = 225 elif engineer_level == 'Senior Solutions Engineer': wage = 275 elif engineer_level == 'Solutions Architect': wage = 275 total = wage * hours context = {'total': total} return render(request, 'website/presales_total.html', context) presales.html <div class="field"> <div class="control"> <input class="input" name="hours" id="hours" placeholder="Hours"> </div> </div> <label class="label">Engineer Level:</label> <div class="field"> <div class="select"> <select name="selected_engineer_level" id="selected_engineer_level"> <option value="">Engineer Level</option> <option value="PM">PM</option> <option value="Solutions Technician">Solutions Technician</option> <option value="Solutions Engineer">Solutions Engineer</option> <option value="Senior Solutions Engineer">Senior Solutions Engineer</option> <option value="Solutions Architect">Solutions Architect</option> </select> </div> </div> </div> <div class="field"> <div class="control"> <button class="button is-info" type="button">Add Task</button> </div> </div> <span class="label is-medium is-pulled-right">Total: {{ total }}</span> presales_total.html Total: <span>{{ total … -
Error when making a POST Request in C# to Django REST API
I would like to make a POST Request to a Django REST API. My data (a Json string) lives in a C# application. I am using this snippet: var httpWebRequest = (HttpWebRequest)WebRequest.Create(myurl); httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"a\":\"sun\", \"b\":\"moon\"}"; streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } Unfortunately, I am getting this error at the 'var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();' line : System.Net.WebException: 'The remote server returned an error: (405) Method Not Allowed.' I have also checked the logs of the Django API, it is Django that is throwing the 'Method Not Allowed' error. After doing some research, it looks like it is caused by the fact that POST is not allowed in my Django REST application. I have been able to issue GET requests with no problem. For this, in my django REST framework application, I use a retrieve() function inside my views.py file. I also happen to have a create() function in the same views.py file. I thought this function would be able to handle the POST request. However, it does not look like I am even able to get to … -
Returning empty queryset when used __startswith(or similar kind) while querying mogodb through parsepy
I am accessing mongodb through parsepy in my django application. I have a name field in my db collection. I'm tying to get those name fields which match my query string. For example, if I have these values--> food, folk, form, fill, filled, dust If I query fo I should get food, folk, form. If I query fi I should get fill, filled I found that CollectionName.Query.filter(name__startswith=query) could do that. But unfortunately that is giving me empty queryset. I tried it with CollectionName.Query.filter(name=ExactNameInDB) like CollectionName.Query.filter(name='food') and it returned me the collection object with that name. I even tried name__contains as keyword argument but that didn't work. This one is bugging me since a long time. Please help me. If you think that this explanation isn't enough, I can elaborate the context more. Thanks in advance :) -
Add task from web interface without restarting celery - django
I am trying to create network scanner, so my goal is to allow user that he can schedule network scan, which is repeated every 30 or 60 minutes depends on what user choice. Currently I am using celery 4.3 and rabbitmq and I can schedule task if I hardcode the time period when the scan will be repeated and network ip address. I would like to add new task to CELERY_BEAT_SCHEDULE when user enter the network ip and the time period in the web browser. Is it possible to add the task and if it possible do I need restart the celery to add new task? Here is my code: setting.py: CELERY_BROKER_URL = 'amqp://localhost' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'scan_network.tasks.scan_network_periodically', 'schedule': crontab(minute='*/30'), 'args': ("192.168.0.0/24") } } celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'network_scanner.settings') app = Celery('network_scanner') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @task() def scan_network_periodically(ip_addres): ... some logic to scan the network I will appreciate any advice how can I achieve my goal. -
Django filtered queryset in foreignkey lookup
I have a standard model with a foreignkey, in this case from biology: Seed to Taxon. The taxon model includes both Animal and Plant Taxon, and has a category column which is either zoology or botany When I add a new Seed I get the expected dropdown list, but it supplies the zoology and botany options. How do I filter it so only the botany options are shown? I'm assuming this filter can be applied somewhere in the model? I've tried adding .filter() and .exclude() but they do nothing here. class Taxon(models.Model): taxon_id = models.AutoField(primary_key=True) taxon = models.CharField(max_length=50, blank=True, null=True) common_name = models.CharField(max_length=50, blank=True, null=True) taxon = models.CharField(max_length=50, blank=False, null=False) genus = models.CharField(max_length=50, blank=True, null=True) category = models.CharField(max_length=50, blank=True, null=True) # family_name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return str(self.taxon) class Meta(): managed=False db_table = 'kap\".\"taxon_manager' ordering = ["genus","taxon"] verbose_name_plural = "taxon" class Seed(models.Model): seed_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', blank=True, null=True, on_delete = models.PROTECT) taxon_id = models.ForeignKey(Taxon, db_column='taxon_id', blank=True, null=True, on_delete = models.PROTECT, related_name='seed_taxon') weight_type = models.CharField(max_length=50) weight = models.DecimalField(max_digits=10, decimal_places=3) quantity_type = models.CharField(max_length=50) quantity = models.IntegerField() def __str__(self): return str(self.taxon_id) class Meta(): managed=False db_table = 'kap\".\"seed' ordering = ["taxon_id","fraction_id"] verbose_name_plural = "seeds" -
How to get the info parameter which is sent to resolver in tests
I want to test test a function that checks if a field is requested by the query: def field_in_query(field, info): fragments = {} node = ast_to_dict(info.field_asts[0]) for name, value in info.fragments.items(): fragments[name] = ast_to_dict(value) while node.get('selection_set'): for leaf in node['selection_set']['selections']: if leaf['name']['value'] == field: return True else: node = fragments[leaf['name']['value']] if leaf['kind'] == 'FragmentSpread' else leaf return False but i don't know how to get the info parameter. Is there any way to do it?