Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project can work in pycharm, But it raise error when I runserver in cmd
runserver in cmd raise error like this that is wrong D:\Documents\DictOnline>workon dictonline (dictonline) D:\Documents\DictOnline>python manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x0000016C56481400> Traceback (most recent call last): File "D:\Documents\envs\dictonline\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "D:\Documents\envs\dictonline\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\checks\urls.py", line 10, in check_url_config return check_resolver(resolver) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\checks\urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "D:\Documents\envs\dictonline\lib\site-packages\django\utils\functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\Documents\envs\dictonline\lib\site-packages\django\utils\functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "D:\Documents\envs\dictonline\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "D:\Documents\envs\dictonline\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "D:\Documents\DictOnline\DictOnline\urls.py", line 20, in from users.views import IndexView,LoginView File "D:\Documents\DictOnline\apps\users\views.py", line 20, in from utils.email_send import send_email File "D:\Documents\DictOnline\apps\utils\email_send.py", line 13, in from settings import EMAIL_FROM ModuleNotFoundError: No module named … -
Django password reset using user's stored email instead of user input
I am using the default Django password reset system, which has the following workflow: User clicks 'reset password' link User enters email on a page User is sent password reset link to address entered in previous step I would like this to be: User clicks 'reset password' link User is sent password reset link to email used to create user account I already have the former set up, but I can't find a way to change the password reset function to pull the user email from the user model and use that instead of an email that the user enters. Any ideas? -
Why are my Angular routes not connecting to my backend Django routes?
I've been trying to have a simple Get Request work with my Angular/Django setup but the route doesn't seem to be able to find the Backend Django routes. I am passing the data as a query string parameter. At first it was giving me an error which I fixed using this thread: Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON Now it doesn't give me any error at all. However, I know it never finds my route in my Backend Django. I've been trying to solve this simple error for 3 days now, any help would be appreciated. The route I am on: http://127.0.0.1:8000/registration user.service.ts: export class UserService { httpHeaders = new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'}) constructor(private _http : HttpClient) { } checkEmailNotTaken(values: any): Observable<any> { console.log("SERVICE: Check Email"); console.log(values); let params = new HttpParams(); params = params.append('email', values); return this._http.get('/UserEmail/', {headers: this.httpHeaders, params: params, responseType:'text' as 'json'}); } } urls.py: urlpatterns = [ path('UserEmail/<email>', viewsCRUD.getUserByEmail) ] views.py: @api_view(['GET', 'POST']) def getUserByEmail(request): print(request) print(request.GET) Python/Django Terminal: [11/May/2019 21:14:21] "GET /UserEmail?email=david@g HTTP/1.1" 200 831 -
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host - django
I am getting below issue while processing paytm payments and returning back to my Django application. Here's my code. [12/May/2019 08:38:35] "POST /paytm/payment/ HTTP/1.1" 200 4005 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 54543) Traceback (most recent call last): File "C:\Python\Python37\lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "C:\Python\Python37\lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python\Python37\lib\socketserver.py", line 717, in __init__ self.handle() File "C:\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host ---------------------------------------- [12/May/2019 08:39:25] "POST /paytm/response/ HTTP/1.1" 200 3154 Transaction should complete without any exceptions. In local I'm getting response from Paytm even with the error. But In live website, transaction happening without any response from Paytm. I hope because of the above exception no response in website and it's automatically returning to home page. Need help ASAP. Thanks in Advance. -
Dynamically populate ChoiceField Formset in Formwizard
I'm trying to populate a ChoiceField in a FormSet with info from a previous step (a bit relevant to my last asked question). I'm almost there, but can't seem to initialize the list: def get_form(self, step=None, data=None, files=None): form = super(FormWizardView, self).get_form(step, data, files) step = step or self.steps.current if step == 'pages': form_class = self.form_list[step] form1_cleaned_data = self.get_cleaned_data_for_step('agenda') formset = PagesFormSet() loan_choices = [] for form in formset.forms: if form1_cleaned_data: form.fields['agenda_select'].choices = [item for item in form1_cleaned_data.items()] # print(form.fields['agenda_select']) return PagesFormSet(data = data) return super(FormWizardView, self).get_form(step, data, files) The list just doesn't show. However, printing in the console does work. If I just return formset instead of PagesFormSet, the list does populate. However, the list is then not valid and I can't continue to the next step (also the case if I add data = data then. I think I should add some extra info to the return PagesFormSet(data = data), but I just don't have a clue. I would love some help as I have been staring for a day at this problem. Many thanks! -
Calculate sum for different data types in Django
I have columns in db called as Price and Qty. Price is the textfield because it requires to be written as $ 12 (for example). While Qty is integer. But when i run my code. it shows an error sum_count = OrderItem.objects.filter(OrderId=OrderId).aggregate(total_price=Sum('Total_Price:' 'Price[2:]' * 'Qty')) TypeError: can't multiply sequence by non-int of type 'str' models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) FoodId = models.TextField() Item = models.TextField() Qty = models.IntegerField(blank=False) Price = models.TextField() TotalPrice = models.TextField() Note = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=100, null=True) views.py def cashier(request): chef_view = OrderItem.objects.all() OrderId = request.POST.get("OrderId") sum_count = OrderItem.objects.filter(OrderId=OrderId).aggregate (total_price=Sum('Total_Price:' 'Price[2:]' * 'Qty')) context = { 'chef_view': chef_view, 'total': total } #total = OrderItem.objects.aggregate(Sum("Price")) return render(request, 'restaurants/cashier_page.html', {'context':context}) cashier_page.html <form action="#" method="post"> {% csrf_token %} {% for order in context%} <table width="800"> <tr> <th width="800">Table Number</th> <th width="800">Item</th> <th width="800">Quantity</th> <th width="800">Price</th> <th width="800">Order Id</th> <th width="800">Total Price</th> </tr> <tr> <td width="800">{{ order.Table_No }}</td> <td width="800">{{ order.Item }}</td> <td width="800">{{ order.Qty }}</td> <td width="800">{{ order.Price }}</td> <td width="800">{{ order.OrderId }}</td> <td width="800">{{ order.TotalPrice }}</td> </tr> </table> {% endfor %} </form> The result should be able to do the total_price calculations based on OrderId and show it to the template. Anyone can help me to … -
Calculate the lenght of list items with Javascript
I have setup a Javascript function that generate random numbers for every of my search results which are list items and I want to calculate the lenght of the list without knowing in advance the number of search results that will be displayed since every queries are different. Is there any ways to do that? Currently, I add a number to itemLength manually within this Javascript function because I know the number of results for a particular query: <script type="text/javascript"> var orderedList = document.getElementById("my_list"); var itemLength = 8; //REPLACE THIS WITH THE LENGTH OF THE ITEM LIST function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } // get a default 100 into the array var arrayOfNumbers = [100], listItem = document.getElementById("list_item"); // get itemLength random numbers for (let i = 0; i < itemLength; i++) { arrayOfNumbers.push(getRandomInt(30, 98)) } // sort the array of random numbers arrayOfNumbers.sort(function(a, b) { return b - a }) // now do the lopping and creating elements for (let i = 0; i < arrayOfNumbers.length; i++) { let randomIntContainer = document.createElement('div'); randomIntContainer.textContent = arrayOfNumbers[i] + "%"; randomIntContainer.setAttribute('class', 'number'); listItem = document.getElementById("list_item"); listItem.appendChild(randomIntContainer); orderedList.appendChild(listItem); … -
How can I hit Django api with parameters using Postman?
@must_be_admin_user def patch(self,request,category_id): ''' Updates Data in the Category Parameters Authenticated Admin User , category_id ''' category = get_object_or_404(Category, id=category_id) # IF admin is not the Creater of the Category if category.created_by != request.user.id: Response(status=status.HTTP_400_BAD_REQUEST, data={"error": "You did not Create this so you cant delete this"}) category.last_updated = timezone.now() updated_category = CategorySerializer( category, data=request.data, partial=True) if updated_category.is_valid(): updated_category.save() return Response(status=status.HTTP_201_CREATED, data=updated_category.data) return Response(status=status.HTTP_400_BAD_REQUEST, data={"error": updated_category.errors}) I want to know how to send category_id using postman . I am facing issues hitting this api using postman -
How to allow blank field on OneToOne serializer field for Django REST Framework API?
When POSTing to my API endpoint I get a field is required error on a OneToOne field, but I create the OneToOne Field in the save() method of the model I'm POSTing. I've tried setting default=None, null=True, and blank=True Device Model class Device(models.Model): name = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) brand = models.TextField(max_length=50) year_purchased = models.IntegerField() serial_number = models.TextField(max_length=100) info = models.TextField(max_length=100) qrcode = models.ImageField(upload_to='', blank=True, null=True) def save(self, **kwargs): super(Device, self).save(**kwargs) if not self.qrcode: self.generate_qrcode() if not self.checkouts.exists(): checkout = Checkout(item=self) checkout.save() Checkout Model class Checkout(models.Model): status_choices = (...) # Fields slug = extension_fields.AutoSlugField(populate_from='item', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) due_back = models.DateField(null=True, blank=True) checked_out = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=2, choices=status_choices, default=in_stock) # Relationship Fields user = models.OneToOneField( DeviceUser, on_delete=models.CASCADE, related_name="checkouts", blank=True, null=True, default=None, ) item = models.OneToOneField( Device, on_delete=models.CASCADE, related_name="checkouts", primary_key=True, blank=True, default=None, ) When POSTing http POST http://localhost:8000/main/api/device/ brand=test2 info=123213123 name=test2 serial_number=12321321 year_purchased=12 'Authorization: Token .....' I expect to get a confirmation that a device was created, instead I get "checkouts": [ "This field is required." ] -
Getting daphne to run automatically
I am trying to run daphne on it's own. My server is running UWSGI and NGINX which is working 100%. When I run the following command: daphne -b 0.0.0.0 -p 8001 yolkichat.asgi:application Everything works perfectly. I have tried a bunch of tutorials which brought me no where. I have tried creating a service file using: systemd and then creating the .sh script but does not work. Code of systemd file below: systemd service file [Unit] Description=Yolkichat service After=network.target StartLimitIntervalSec=0 [Service] Type=simple Restart=always RestartSec=1 User=darren ExecStart=/bin/bash /home/darren/yolkichat/ ./yolkwebsocket.sh [Install] WantedBy=multi-user.target NGINX FILE: server { server_name yolkichat.com www.yolkichat.com; location /static { ... } location /media { ... } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/yolkichat.sock; } location /ws { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://unix:/run/uwsgi/yolkichat.sock; proxy_read_timeout 86400s; proxy_send_timeout 86400s; } } -
Float value not saving
My application is trying to save a float value. But it is throwing an exception called this <class 'decimal.InvalidOperation'>. The model decimal field is defined with max_digits=19 and decimal_places=10. models.DecimalField(max_digits=19, decimal_places=10) The amount which is trying to save in the database is 16097141137.957886. Not sure what could be the issue. Can someone point me what I was doing wrong or how can I fixed this -
How to pass pk of detail view into fk of form
Good afternoon, I am fairly new to Django and I am not sure how to go about this.I have a Django 2.2 project with these models: class Equipment(models.Model): name = models.CharField( max_length=15, unique=True, verbose_name='asset name') asset_cat = models.ForeignKey('category',on_delete=models.PROTECT,verbose_name='asset category') asset_loc = models.ForeignKey('location',on_delete=models.PROTECT,verbose_name='asset location') state = models.ForeignKey('status',on_delete=models.PROTECT,verbose_name='status') brand = models.CharField( max_length=15, unique=False, blank=True) model = models.CharField( max_length=12, unique=False, blank=True, verbose_name='model number') def __str__(self): return "{}".format(self.name) def get_absolute_url(self): return reverse('equipment-detail', args=[str(self.id)]) class Meta: ordering = ['asset_cat', 'name'] verbose_name_plural = 'pieces of equipment' class Action(models.Model): name = models.ForeignKey('equipment',on_delete=models.PROTECT,verbose_name='asset name',blank=False) dt = models.DateTimeField( auto_now_add=True, verbose_name='date and time of incident') incident = models.TextField( blank=True, null=True) CHANGE = 'CHANGE' SERVICE = 'SERVICE' ACTION_CHOICES = ( (CHANGE, 'CHANGE'), (SERVICE, 'SERVICE') ) act = models.TextField( blank=True, choices=ACTION_CHOICES, null=True, verbose_name='action taken') act_detail = models.TextField( verbose_name='action detail', blank=False) result = models.TextField( blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('service-detail', args=[str(self.id)]) class Meta: ordering = ['-dt'] verbose_name_plural = 'service calls' I have an Equipment Detail View like this: class EquipmentDetailView(generic.DetailView): model = Equipment template_name = 'equipment_detail.html' def get_context_data(self, **kwargs): context = super(EquipmentDetailView, self).get_context_data(**kwargs) return context The detail view has two buttons: edit and service. If I click edit I have a model form that allows me to edit that … -
Inconsistent redirect
I want to have a message based on the type of button I click. Instead, django reacts strangely when I click a button and send me another page that is not supposed to show. Urls.py re_path(r'^liste-ue/$', views.liste_ue, name="liste_ue"), re_path(r'^ajouter-ue/$', views.ajouter_ue, name="ajouter_ue"), re_path(r'^modifier-ue/(?P<code>[a-zA-Z0-9 .-]{4,10})/$', views.modifier_ue, name="modifier_ue"), Views.py # La view pour qui permet de lister et de créer des UEs. Seul les administrateurs y ont accèes. def liste_ue(request): ues = UE.objects.all(); return render(request, 'felyn/admin/liste_ue.html', {'ues': ues}); # La view qui permet d'ajouter les UEs. seul les administrateurs y ont accès. def ajouter_ue(request): if request.method == 'POST': ue_form = UEForms(request.POST); if ue_form.is_valid(): code_ue = ue_form.clean_code_ue(); intitule_ue = ue_form.clean_intitule_ue(); semestre = ue_form.cleaned_data['semestre']; if 'continuer' in request.POST: ue_form.save(); ue_form = UEForms(); return render(request, 'felyn/admin/ajouter_ue.html', {'ue_form':ue_form}); elif 'quitter' in request.POST: ue = ue_form.save(); ues = UE.objects.all(); return render(request, 'felyn/admin/liste_ue.html', {'ues': ues}); else: return render(request, 'felyn/admin/ajouter_ue.html', {'ue_form': ue_form}); else: ue_form = UEForms(); return render(request, 'felyn/admin/ajouter_ue.html', {'ue_form': ue_form}); # La view qui permet de supprimer une UE def modifier_ue(request, code): if request.method == 'POST': ue_form = UEForms(request.POST); if ue_form.is_valid() and 'supprimer' in request.POST: return HttpResponse('supprimer'); elif ue_form.is_valid() and 'continuer' in request.POST: return HttpResponse('continuer'); elif ue_form.is_valid() and 'quitter' in request.POST: return HttpResponse('quitter'); else: return render(request, 'felyn/admin/ajouter_ue.html', {'ue_form': ue_form}); … -
How to use canvas drawing as an input to a Classifier resides in Django Views.py
I have made the html page for canvas drawing but now i want to use drawn image on canvas as an input to my classifier using django, i don't know how transfer the image data and what to write in django views to retrieve the image data HTML Code - <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Draw Number</title> </head> <body> <canvas id="canvas" width="600" height="600" style="border: 1px solid black;"></canvas> <script src="canvas.js"></script> <button onclick="myFunction()">Reset</button> <script > function myFunction(){ var canvas= document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); } </script> </body> </html> Javascript Code- window.addEventListener("load",()=>{ const canvas=document.querySelector("#canvas"); const ctx=canvas.getContext("2d"); let painting=false; function startPosition(e){ painting=true; draw(e) } function finishedPosition(){ painting=false; ctx.beginPath(); } function draw(e){ if(!painting) return; ctx.lineWidth=7; ctx.lineCap="round"; ctx.lineTo(e.clientX,e.clientY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.clientX,e.clientY); } canvas.addEventListener("mousedown",startPosition); canvas.addEventListener("mouseup",finishedPosition); canvas.addEventListener("mousemove",draw); }) -
Correct design in Django to handle forms and views depending on the type of user
Problem I'm writing an application in Django that connects students with tutors. There are three main models: Student, Tutor, and Coordinator. The problem is that the website in itself is pretty similar for all three types of models, but each varies a bit on what they actually get to do or see. For instance, all three types of user can book a class via the BookClassForm. However, the Coordinator can assign a tutor and student, while a tutor and student cannot. Or for example a Coordinator can see all the classes from all students and tutors on the calendar view, while a student only sees his classes. In general does this mean I should write three separate forms or one form that makes some inputs optional for each type of user? Do I write three templates or one template where I put the logic for each type of user? Do I write three views that handle each type of user or one main view? Do I write three apps for each type of user or one main app? I'm ending up with this really big application with a lot of views and repetitive code and I don't really know what … -
Send a post request from an expressjs router to django
I am trying to implement the following workflow. Populate an html form Submit it The endpoint that is receiving the request(expressjs) does some processing and sends a request with the req.body to another backend(django) Django returns a response to expressjs The problem is that I am being stuck at the csrf level and more specifically getting this error: invalid csrf token 403 ForbiddenError: invalid csrf token Here is the code that I am using for the request: router.post('/registration', function (req, res, next) { axios.post('http://localhost:8000/register_extended/', JSON.stringify(req.body), { 'Content-Type': 'application/json' }).then(() => { console.log('success') }).catch(() => { console.log('failure') }) res.send('respond with a resource'); }); }); and here are my middlewares app.use(bodyParser.urlencoded({ extended: true })); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(csrfMiddleware); How can I provide a valid csrf token for my needs? Axios is supposed to the handling itself, thats why I chose it. -
Why use sessions for shopping carts?
Currently am learning django and am wondering why do most courses use sessions for shopping cart and not just store these to the database. -
How to run view after browser page return?
I am creating a shopping cart with Django In my template checkout.html I receive template tags. Then I submit a form using Ajax. When I click the button to go to the next page ( payment.html ) everything works well, but if I click the browser button to go back to previous page, I will get the same template tags in checkout.html, because the view that returns checkout.html doesn't get executed. I need it to be updated, because I modify the expected results through ajax. I have solution for this, but messy. which is to create a session storage variable with a flag initially disabled. The flag is enabled when the user goes to checkout.html, and disabled when the user goes to payment.html, then on javascript ready function I check the flag, and if it's enabledI will use jquery to submit a form with the action to the view that returns checkout.html and therefor I will have the new template tags in checkout.html; I'm looking for a more simple/clean solution I avoided posting code because it's long, but if I will if required. -
How to combine 2 different models with a 'Model in the middle'?
I'm creating a HTML table which will show available stock of a list of products in different warehouses. But a product is (ofcourse) not directly bound to a warehouse. This is bound with a third model stock. The idea is that I create the table and in the left most column you'll have the list of products, with vertical columns with the warehouse stock. The problem comes when not all warehouses are able to have this product. So'll they won't appear in the database. I've already succesfully tried something and it does work, but I feel like it's really bad code. Definitely since Django Templates are supposed to be as easy as possible. This is not: class Product(models.Model): name = models.CharField(.... class Warehouse(models.Model): name = models.CharField(.... class Stock(models.Model): product = models.ForeignKey(Product... warehouse = models.ForeignKey(Warehouse... quantity = models.CharField(.... @register.simple_tag # I'll get to this def get_k_v(l, key, v): try: return l.get(**{key: v}) except: return None What I do now is, I loop over the Products and inside of each row loop over all the warehouses using a callback to a function, if it exists I show the quantity if it doesn't the cell will become gray (for now, might change). Visualization: … -
Joining models in django through 2 ForeignKeys
Is there a possibility in Django to create a query that would uses two ForeignKeys to create a join between tables? To illustrate what I mean suppose I have the following models in Django: class Author(models.Model): name = models.TextField() class Publisher(models.Model): name = models.TextField() class BooksSold(models.Model): author = ForeignKey(Author, related_name='books_sold') publisher = ForeignKey(Publisher, related_name='books_sold') books_sold = models.IntegerField() class BooksPrinted(models.Model): author = ForeignKey(Author, related_name='books_printed') publisher = ForeignKey(Publisher, related_name='books_printed') books_printed = models.IntegerField() I would like to join the BooksSold and BooksPrinted tables using the Author and Publisher keys. In sql it would be: SELECT A.author_id ,A.publisher_id ,A.books_sold ,B.books_printed FROM table_books_sold A INNER JOIN table_books_printed ON A.author_id = B.author_id AND A.publisher_id = B.publisher_id The method I am currently using is to iterate over one of the models join in through one of the ForeignKeys and filter with the other ForeignKey, which would be for this example: def get_books_printed(books_sold_model): return next(b for b in books_sold_model.author.books_printed if b.publisher_id = books_sold_model.publisher_id books_sold_models = BooksSold.objects.all().prefetch(author__books_printed) for book_sold_model in books_sold_models: books_printed = get_books_printed(books_sold_model) I would like to know if is there is a way to avoid iterating through all of the instances until I find the match with the other ForeignKey -
in models.py when is set to_field_name to more than one column name, it's giving me error
I have created a label_form_instance for modelchoicefield but the values in html are showing primary key values. To, get rid of that i use to_field_names but i can't provide more than one column name in it. class firearmChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return '%s%s, %s'%(obj.make,obj.firearm_model,obj.serial_no) self.fields['firearm'] = firearmChoiceField(queryset = firearm_db.objects.all(),to_field_name="make,firearm_model,serial_no",required=False,empty_label='Select Firearm', widget = forms.Select(attrs={'label': ' ','class': 'form-control',})) -
Ansible script in celery task not working
Code Snipet class ResultsCollector(CallbackBase): def __init__(self, *args, **kwargs): super(ResultsCollector, self).__init__(*args, **kwargs) self.host_ok = {} self.host_unreachable = {} self.host_failed = {} def v2_runner_on_unreachable(self, result): self.host_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs): self.host_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs): self.host_failed[result._host.get_name()] = result @task(bind=True, name="ansible_job") def ansible_job(self, data, service_type): from collections import namedtuple from ansible.executor.task_queue_manager import TaskQueueManager from ansible.inventory.manager import InventoryManager from ansible.parsing.dataloader import DataLoader from ansible.playbook.play import Play from ansible.plugins.callback import CallbackBase from ansible.vars.manager import VariableManager host_list = ["hosts1", "hosts2"] Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check', 'diff']) loader = DataLoader() options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100, remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None, become_user=None, verbosity=None, check=False, diff=False) passwords = dict() inventory = InventoryManager(loader=loader, sources='/etc/ansible/hosts') variable_manager = VariableManager(loader=loader, inventory=inventory) play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module='setup', args=dict()))] ) play = Play().load(play_source, variable_manager=variable_manager, loader=loader) callback = ResultsCollector() tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords, ) tqm._stdout_callback = callback result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() return result code is celery task. python code is working fine. but when i run same code through celery ansible is not working Note: Celery 4.2 Ansible … -
How to trigger saving a field in another table when data in one table is saved in the Django Admin inerface?
These are my models. class User(models.Model): USER_TYPES = ( ('P', 'Professor'), ('S', 'Student') ) user_type = models.CharField(max_length=1, choices=USER_TYPES) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) ... class StudentDetail(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ... class ProfessorDetail(models.Model): professor = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ... I am using the DjangoAdmin interface to populate these tables. Is there a way to trigger a request to save data in another table when data in one table is saved? I want to be automatically redirected to entering data for either StudentDetail or ProfessorDetail based on the value that is saved in the User table. I want this to happen in the Django admin interface. Otherwise, this would be pretty simple. -
Django / Wagtail Navigation Bar with Dropdown Creates More Items than Expected
I want to create multiple submenus for different pages of a website. So, I created a snippet called "Submenus". The submenu contains an object called submenu_items. On the webpage, that translates to the top level of navigation. Then, each submenu_item has a dropdown_items. That way, under each top level link, I can create a dropdown with more links. Problem: Whenever I create a new submenu_item, it creates 3 dropdown_items (example in photo below). I tried deleting them, saving the snippet. But when I click on the snippet, they are there again. I tried recreating the entire model and re-migrating everything. I still get the same problem. Can someone point out what I may be doing wrong? Is there some rule for nested elements I'm missing? @register_snippet class Submenu(ClusterableModel): text = models.CharField(max_length=255) subsite_url = models.CharField(max_length=255) panels = [ FieldPanel('text'), FieldPanel('subsite_url'), InlinePanel('submenu_items', label="Submenu Items"), ] def __str__(self): return self.text class SubmenuItem(ClusterableModel, Orderable): page = ParentalKey(Submenu, on_delete=models.CASCADE, related_name='submenu_items') menu_item = models.CharField(blank=True, max_length=250) internal_url = models.CharField(blank=True, max_length=250) panels = [ FieldPanel('menu_item'), FieldPanel('internal_url'), InlinePanel('dropdown_items', label="Dropdown Items"), ] class DropdownItem(Orderable): page = ParentalKey(SubmenuItem, on_delete=models.CASCADE, related_name='dropdown_items') menu_item = models.CharField(blank=True, max_length=250) internal_url = models.CharField(blank=True, max_length=250) panels = [ FieldPanel('menu_item'), FieldPanel('internal_url'), ] -
Cannot download psycopg2 package MacOS
im trying to pip3 install psycopg2 in terminal and im getting big message about some errors that i cant fix Im already tried to xcode-select --install - answer is xcode-select: error: command line tools are already installed, use "Software Update" to install updates Now im downloading xcode from appstore, but meanwhile i want to hear your guesses about this there is a piece of messages for more you can go here pip3 install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/23/7e/93c325482c328619870b6cd09370f6dbe1148283daca65115cd63642e60f/psycopg2-2.8.2.tar.gz Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Complete output from command /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/xx/j_b79v953x9cmw8tprb4t_jr0000gn/T/pip-install-e6hjvqzq/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/xx/j_b79v953x9cmw8tprb4t_jr0000gn/T/pip-wheel-k9mljs3g --python-tag cp37: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.7 creating build/temp.macosx-10.9-x86_64-3.7/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 …