Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle several search fields on one page using raw sql?
I have for now two serach field(planning to add more) and I want to use only raw sql whem filtering the objects(I know that Django provides ORM which makes life so much easier, but in my work right now I need to use SQL) I know how to do it with ORM in Django,like this: def my_view(request): value_one = request.GET.get("value_one", None) value_two = request.GET.get("value_two", None) value_three = request.GET.get("value_three", None) objects = MyModel.objects.all() if value_one: objects = objects.filter(field_one=value_one) if value_two: objects = objects.filter(field_two=value_two) if value_three: objects = objects.filter(field_three=value_three) But is there a way to use SQL instead of filtering? def profile(request): cursor = connection.cursor() value_one = request.GET.get("searchage", None) value_two = request.GET.get("search", None) objects= cursor.execute('SELECT * from People p JOIN Jobs j on p.JobId = j.Id ') objects = dictfetchall(cursor) if value_one: objects = cursor.execute('SELECT * from People p JOIN Jobs j on p.JobId = j.Id WHERE p.Age = %s',[value_one] ) if value_two: objects = ??? return render(request,'personal.html', {'value1':value_one, 'value2':value_two, 'objects':objects}) I have only one idea and it's to have if clause like this if value_one and value_two: .. elif value_one and !value_two: ... elif !value_one and value_two: But if I have more than 2 search fields it gets kind of difficult … -
Taking input as argument for another script in Python
I have a python script with a main method that takes input. Now I need to use this input as an argument for another script without a main method. The first script is Django so it takes input on a webpage and when this input is submitted, the second script should take this input as a parameter and execute itself. The second script is a socket listener. Can someone help with this? Thank you -
Comment not being added to the database
I am working on a movie website with Django and I'm trying to add user comments. Only the registered users should be allowed to comment. I have the following so far: models.py: class Comment(models.Model): movie = models.ForeignKey(Movie, related_name = "comments", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.movie.title, self.name) forms.py class CommentForm(forms.ModelForm): content = forms.CharField(label ="", widget = forms.Textarea( attrs ={ 'class':'form-control', 'placeholder':'Comment here!', 'rows':5, 'cols':50 })) class Meta: model = Comment fields =['content'] views.py class MovieDetailsView(generic.DetailView): model = Movie template_name = "details.html" def comment(request, id): movie= Movie.objects.get(id) if request.method == 'POST': cf = CommentForm(request.POST or None) if cf.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(movie = movie, user = request.user, content = content) comment.save() return redirect(movie.get_absolute_url()) else: cf = CommentForm() context ={ 'comment_form':cf, } return render(request, 'details.html', context) details.html <form method="POST" action="#" class="form"> {% csrf_token %} {{comment_form.as_p}} <button type="submit" class="btn btn-primary btn-lg">Submit</button> <textarea id="text" name="text" class="form__textarea" placeholder="Add comment"></textarea> <button type="button" class="form__btn">Send</button> </form> The MovieDetailsView displays the details page of the movie and has a comment section. However, when I submit the comment, it simply displays a white page and this link: http://127.0.0.1:8000/details/1# . The comment is not … -
Sending data from computer to django website
I work at a computer repair shop. We have a lot of computers we work on that we collect information from. CPU, GPU, RAM, HD space, etc. I wrote a python script that can capture all that information. Now I want to know how I can automatically send that information to a django site and store it in the database. I want the program to ask for the customer id and the asset id and set pass that information along as well. If the computer doesn't have internet, I want it to send it once it gets internet. Then I'm thinking on the server, I'll run the logic to checks if the information is valid (if the computer already exists in the database). How would I begin to start something like this? Is this socket programming? Can you point me in the right direction? -
django on_delete when adding post author
for the on_delete I am seeing this error: File "/home/kensei/Documents/school/bubbles/models.py", line 11, in bubbles user = models.ForeignKey(settings.AUTH_USER_MODEL,) TypeError: __init__() missing 1 required positional argument: 'on_delete for this file in my app from django.conf import settings # Create your models here. class bubbles(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,) content = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.content) ``` even with several alterations attempting to add on_delete -
Python ( PIL ) '<_io.BufferedReader' error
specs ubuntu 18.04 ( VPS ) django python 3.8 Error: File "/django/venv/lib/python3.6/site-packages/PIL/Image.py", line 2931, in open "cannot identify image file %r" % (filename if filename else fp) PIL.UnidentifiedImageError: cannot identify image file <_io.BufferedReader name='/django/wall/media/wallpaper.jpg'> this error occurred while I was processing an image with help of Django-imagekit i m processing 1000's of images but this error occurs only on few, rest works fine -
Insert a dictionary in all data of a django queryset
I am getting the Django Query Set output like this. <QuerySet [ { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 47, 66880, tzinfo=<UTC>), 'coin': 200 },{ 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 54, 132439, tzinfo=<UTC>), 'coin': 150 }]> I want to insert a key value pair in all quesryset inside the list. The desired output should be. <QuerySet [ { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 47, 66880, tzinfo=<UTC>), 'coin': 200, 'transiction_type':'credit' }, { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 54, 132439, tzinfo=<UTC>), 'coin': 150, 'transiction_type':'credit' } ]> I have done this By this way. coin_withdraw_list = [dict(coin_withdraw, transaction_type="CREDIT") for coin_withdraw inuser_withdraw_list] But I am looking for if their any way to do this using any django function. Thanks in advance. -
How can I capture the name or reg_no of the book in this list?
I'm working on a library system. I am unable to get the registration number of a book/books to be returned back to library... My intention is to click on Return which captures the book name for return processing.. With what I have, when I print(book) it returns None meaning nothing has been taken from the click My models class Books(models.Model): DEPARTMENT = ( ('COM', 'Computer'), ('ELX', 'Electronics'), ('CIV', 'Civil'), ('BBS', 'Business'), ('MSC', 'Miscellaneous'), ) reg_no = models.CharField(max_length=20, blank=True) book_name = models.CharField(max_length=200) no_of_books = models.IntegerField() book_detail = models.TextField(default='text') department = models.CharField(max_length=3, choices=DEPARTMENT) def Claimbook(self): if self.no_of_books>1: self.no_of_books=self.no_of_books-1 self.save() else: print("not enough books to Claim") def Addbook(self): self.no_of_books=self.no_of_books+1 self.save() def __str__(self): return self.book_name class Return(models.Model): return_date = models.DateField(default=datetime.date.today) borrowed_item = models.ForeignKey(Issue,on_delete=models.CASCADE) def new_issue(request): if request.method == 'POST': i_form = IssueForm(request.POST) if i_form.is_valid(): name = i_form.cleaned_data['borrower_id'] book = i_form.cleaned_data['book_id'] i_form.save(commit=True) books = Books.objects.get(book_name=book)#Get a book names as selected in the dropdown semest = Student.objects.get(name=name).semester#Get a student with a semester as selected in the dropdown departm = Student.objects.get(name=name).depart Books.Claimbook(books) return redirect('new_issue') else: i_form = IssueForm() semest = None departm = None sem_book = Semester.objects.filter(sem=semest, depart=departm) return render(request, 'libman/new_issue.html', {'i_form': i_form, 'sem_book': sem_book}) The return view def return_book(request): book = request.GET.get('book_pk') print(book) books = Books.objects.get(id=book) … -
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020B1B5FB640>: Failed to establish a new connectio
I'm new to django and trying to connect django with docker. I'm trying to call docker compase from my django app using url. But docker in port "localhost:5000" and my django app is running on port "127.0.0.1:8000". I think my error is occured from different port numbers. I'm having so much trouble about this issue. How can I solve this error? Please, help. views.py def sentiment(request): output = {} if 'input' in request.GET: input = request.GET['input'] url = 'http://localhost:5000/sentiment/%s' % input response = requests.get(url) user = response.json() return render(request, 'blog/links/Link1.html', {'output': output}) Link1.html <form class="text" method="get" action="{% url 'da_sonuc'%}"> <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Test with your own text...</h2> <input class="input" type="text" name="input"> <br> <button type="submit" class="btn" name="submit" >Try!</button> </form> <label > Result </label> <div class="outcome"> {% if output %} <p><strong>{{ output.text }}</strong></p> {% endif %} </div> Error: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /sentiment/iyi (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020B1B5FB640>: Failed to establish a new connection: [WinError 10061] -
Django How to organize models so there is only one owner
I have two models Company and User: class Company(models.Model): name = CharField("Name", max_length=60) owner = OneToOneField( "Employee", related_name='owner', on_delete=SET_NULL, null=True) class BaseUser(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() join_date = DateTimeField(default=timezone.now) name = CharField("Name", max_length=60) email = EmailField(('Email'), unique=True) company = ForeignKey(Company, on_delete=models.CASCADE) I need to have only one User as owner. I made it so two models point to each other which doesn't seem right. Is there a way to fix it and still have only one possible owner? I know standard way would be to add is_owner = Boolean to User but it allows other Users to be owners. -
django form not saving new user is user model
I've made this Signup form in django but the problem is whenever I hit register button it does not save anything on the user model in my admin. Please do help to solve the problem. Forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate class register(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Views.py from django.shortcuts import render, redirect from .models import mypost from .forms import register from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate def signup(req): if req.method == 'POST': form = register(req.POST) if form.is_valid(): form.save() return redirect('/') else: form = register() return render(req, 'signup.html',{'form':form}) Signup.html {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock %} {% block body %} {% include 'nav.html' %} <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h3 class="text-center">Sign Up Form</h3> <form method="post">{% csrf_token %} {{form|crispy}} <input type="submit" value="Register"> </form> </div> <div class="col-md-3"></div> </div> </div> {% endblock %} -
How to add site models to Cookiecutter Django project
I have a Cookiecutter Django project in which I'd like to add a "SiteSettings" model to control constants. My first instinct was to run manage.py startapp site. However I received the following message: CommandError: 'site' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. Upon closer inspection, it appears that Cookiecutter already created a sites module within contrib, but with no models.py file. So I decided to make a models.py with the SiteSettings model in this directory. However when I run makemigrations it says: No changes detected in app 'sites' How can I add my desired model to this module and get migrations working for this module? -
How to insert JavaScript object into Django JSONField
In my django web app I have two pages- One is a form for the user to fill out the name, size, image, and specify the names of some points of interest on the image. The next page displays that image and allows the user to place some SVG circles corresponding to the points of interest on top, and when the user submits, I want the form from the first page and a JSONField for the locations of the circles (points of interest) on the image to all get saved into one model. Currently, my solution is a page with the first form, then pass that entire form into the next page. Since I don't want the user to see that form anymore, I put it in a hidden div. I render the image from the form and using JavaScript, I draw the circles where the user clicks. When the submit button is pressed, it runs a function in the script that submits the form for a second time, but updates the JSONField with the locations of all the circles before submitting. The code below works up until the form is submitted, but when I get to the view2 function, … -
check checkboxes for values that exists in a list
I am trying to check checkboxes that have values in a list of strings returned from a ModelForm class. The field is declared in models.py file like this: class IC(models.Model): class Meta: verbose_name = "Get Info" p_data = MultiSelectField("Some data", max_length=255, choices=choices.P_DATA_CHOICES, blank=True, null=True) P_DATA_CHOICES looks like this P_DATA_CHOICES = [ ("ch1", "Choice 1"), ("ch2", "Choice 2"), ("ch3", "Choice 3"), ("ch4", "Choice 4"), ("ch5", "Choice 5"), ] I have this ModelForm class in forms.py that I am implementing to the entire class: class ICForm(ModelForm): class Meta: model = IC exclude = ["fk_field"] def __init__(self, *args, **kwargs): super(ICForm, self).__init__(*args, **kwargs) for i, f in self.fields.items(): f.widget.attrs['class'] = "custom_class" In my template I am generating the checkboxes as such: {% for value, text in ic_modelform.p_data.field.choices %} <li> <input id="value_{{ forloop.counter0 }}" name="{{ ic_modelform.p_data.name }}" type="checkbox" value="{{ value }}" {% if value in ic_modelform.p_data.field.checked %} checked="checked" {% endif %}> <label for="value_{{ forloop.counter0 }}">{{ text }}</label> </li> {% endfor %} If I check a few checkboxes (say Choice 1 and Choice 2) and submit the form, I can see ch1,ch2 in the p_data column of the database, but when I load the page again, their respective checkboxes are not checked. I believe this has … -
JQuery Ajax mangles incoming JSON data
I'm sending a dict through my Django API that looks like this: data = { 'total_sales': total_sales, 'salesperson_sales': salesperson_sales, 'date_range': { 'from_date': from_date, 'to_date': to_date } if from_date and to_date else 'all' } and 'salesperson_sales' is a list of dicts that looks like this: salesperson_sales = [{ 'name': string, 'sales': float, 'sales_percent': float }] I'm calling this route from a JavaScript file on one of my pages using the following code: let get_salesperson_sales = async() => { response = await $.ajax({ type: 'GET', url: `/reports/salesperson-sales/${fromDate && toDate ? `?from_date=${fromDate}&to_date=${toDate}` : ''}`, success: (response) => { document.getElementById('total_rep_sales').innerText = '$'+Number(response.total_sales.toFixed(2)).toLocaleString() }, error: (error) => { errorMessage.innerHTML += '<p>Error getting sales by rep: '+error.responseJSON.details+'</p>' } }) return response } I then use that response data in a promise callback function. Promise.allSettled([...]).then((results) => {sales_data = results[0].value; ...})` The problem is that the data I get in the callback function has 'salesperson_sales' sorted by name, but all other fields are left in place. So if my API returns a list that looks like this: [ {'name': 'Courtney', 'sales': 100, 'sales_percent': 17}, {'name': 'Anthony', 'sales': 200, 'sales_percent': 33}, {'name': 'Blake', 'sales': 300, 'sales_percent': 50} ] Then the data I see in my JavaScript file looks like … -
Passing Django user information to Dash app
I am curious whether it is possible to pass the currently logged in user full name into a Dash app created in Django? Assume you have a simple Dash table integrated into Django: import dash from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd from django_plotly_dash import DjangoDash df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) Are there any way to access the -Django- user information of the person who is logged in? This is just a simple example, but I want to create an SQL folder conditional on user name and user ID located in Django Admin. I solely need to know how to grab the name e.g. "name = request.user.get_full_name" or some type of similar function (in the latter case 'request' is not defined so it does not work). Thanks! -
Django PUT/PATCH request body is empty in RetrieveUpdateAPIView
I'm trying to update user by passing Jwt token in header. But body of my request is empty. View passes empty data to serializer. views.py class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer_data = request.data.get('user', {}) print(f'request data: {request.data}') # prints empty dic {} serializer = self.serializer_class( request.user, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) When I run PUT or PATCH request on Postman, I get unchanged user which is related to a token. postman: Postman django terminal says: Error Can someone explain what am I doing wrong? -
__str__ returned non-string (type bytes)
I'm trying to open the view for my posts but I keep getting the error 'str returned non-string (type bytes)'. I read thhat I should use force_bytes and then unicode but it doesn't seem to be working. How can I fix it? This is the model: class Post(models.Model): """ Post """ category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField('Title', max_length=200) body = models.TextField('Body') reply_to = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='child') created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL'), on_delete=models.CASCADE, related_name='posts') def __str__(self): return force_bytes('%s' % self.title) def __unicode__(self): return u'%s' % self.title -
ordering modelchoicefield in django loses formatting
I wanted to order a list in my form view, and found this post here: How do I specify an order of values in drop-down list in a Django ModelForm? So I edited my code and added the line specialty = forms.ModelChoiceField(queryset ='...') So then I reload the form and the widget is all smoshed and funky looking. I checked the html code and the specialties are indeed in the right order! But it misses the widget definition lower adding the form-control class. I am not sure why. if I remove the line specialty = form.ModelChoiceField then everything looks great aside from the dropdown not being in the right order (alphabetical by name field) Not sure why it is missing that widget definition and attaching the class form-control or the tabindex even. Guessing the specialty = forms.ModelChoiceField is overriding it somehow? class ProviderForm(forms.ModelForm): specialty = forms.ModelChoiceField(queryset = Specialty.objects.order_by('name')) #added this def __init__(self, *args, **kwargs): super(ProviderForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-6' self.helper.field_class = 'col-md-6' self.fields['ptan'].required = False self.helper.layout = Layout( Field('...'), Field('specialty'), FormActions( Submit('save', 'Save'), Button('cancel', 'Cancel'), Button('terminate', 'Terminate', css_class="btn-danger"), ), ) class Meta: model=Provider fields = ( '...', 'specialty' ) widgets = { 'specialty':Select(attrs={ … -
Maintain a subset of Django app along with full app
I'm working on a Django project for a large organization, and the full app will be for internal, private use, while a subset of the view functions and templates will also need to be available publicly. Due to IT constraints, the public portion will be on a different server, and won't be able to use the same files (but it will be able to query the database on the private server). Is there a way to maintain a subset of the app's files on a separate server? For example, if the private version has view functions a, b, and c, the public version will only use c. And the public version will only need the relevant template files, etc. Does Django have some way of accomplishing this? Or Git, somehow (maybe gitignore)? I'm just trying to save myself from having to manually copy all updates from the full version to the partial version. -
How to return the maximum value for a given day in python django
I have two apis that return doctor list and nurses list. Each doctor/nurse has a field amount for the amount of money in their account.My aim is to return the nurse/doctor with the highest amount of money on a given day, since these values will change when money is earned/withdrawn.Basically I need to return the max value from doctors and nurses, and then return the maximum of those two as well.I have tried Max in django and order_by but there seems to be more that I need to do to achieve the desired result.I will appreciate if anyone can spare sometime to take me through how to achieve this.The apis that return this data look smt like: "doctors": [ {"name": kev "amount": 100.00}, {"name": dave "amount": 200.00} ] "nurses": [ {"name": brian "amount": 150.00}, {"name": mary "amount": 90.00} ] -
Django:How to update field value from another model?
I want to update the value of field Availability value from "available" to "issued" in the CylinderEntry model when the user Issued that particular cylinder but I was unable to make the change. here what logic I m executing: class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(pk=self.pk).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName+" issued "+self.cylinder.cylinderId here is cylinderentry model: class CylinderEntry(models.Model): stachoice=[ ('fill','Fill'), ('empty','empty') ] substachoice=[ ('available','Availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId here is issuecylinder model: class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(pk=self.pk).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName+" issued "+self.cylinder.cylinderId help me out make changes in values :) -
I tried running code for my SLAMTECH RPlidar but the lidar doesnt get imported in my python window but it show it has been imported on my terminal
Here is the error File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 224, in process func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 959, in _start self._init_draw() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1703, in _init_draw self._draw_frame(next(self.new_frame_seq())) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1726, in _draw_frame self._drawn_artists = self._func(framedata, *self._args) File "/Users/lkhagvabyambajav/Desktop/rplidar/examples/animate.py", line 14, in update_line scan = next(iterator) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 357, in iter_scans for new_scan, quality, angle, distance in iterator: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 323, in iter_measurments raw = self._read_response(dsize) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 199, in _read_response raise RPLidarException('Wrong body size') rplidar.RPLidarException: Wrong body size and code is from rplidar import RPLidar import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation PORT_NAME = '/dev/tty.usbserial-0001' DMAX = 4000 IMIN = 0 IMAX = 50 def update_line(num, iterator, line): scan = next(iterator) offsets = np.array([(np.radians(meas[1]), meas[2]) for meas in scan]) line.set_offsets(offsets) intens = np.array([meas[0] for meas in scan]) line.set_array(intens) return line, def run(): lidar = RPLidar(PORT_NAME) fig = plt.figure() ax = plt.subplot(111, projection='polar') line = ax.scatter([0, 0], [0, 0], s=5, c=[IMIN, IMAX], cmap=plt.cm.Greys_r, lw=0) ax.set_rmax(DMAX) ax.grid(True) iterator = lidar.iter_scans() ani = animation.FuncAnimation(fig, update_line, fargs=(iterator, line), interval=50) plt.show() lidar.stop() lidar.disconnect() if __name__ == '__main__': run() I didnt write this code it is from https://github.com/SkoltechRobotics/rplidar Im trying to test my lidar to see if it … -
Unable to install dependencies for django_heroku because of lack of pg_config
(Disclaimer: I'm a frontender and don't know much about python; I'm trying to deploy the backend that my partner made to Heroku along with my React build. Apologies in advance if I'm hard to understand/using JS terminology) I'm trying to host a django app on Heroku. If I include import django_heroku django_heroku.settings(locals()) and then try to run the server, I get this error: ModuleNotFoundError: No module named 'django_heroku' This thread reports that it's because of a missing dependency. However, when I try to run pip3 install psycopg2 I get this cascade of errors -- it's like pip is trying to install older and older versions of psycopg2 until it find a match, but each time it errors out. And the error states: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. I don't have a pg_config file/package, nor a steup.cfg or a setup.py package. There is a setuptools_build.py. This thread suggests it's because I don't have postgres installed, but we're not using postgres (we're … -
error with sekizai for adsense when debug = false in my django web app
i'm trying to add google adsense to my django web app and i can't activate my account because of no content on my website. (ah this moment i had only put the script tag that google gave me when i created my account). so i tried to add django ads and sekizai to my app to make adsense work on it. and my problem is that when my debug settings is true and i try to runserver, everything works well, but when i change it to False and try runserver, i've got an 500 error and i don't understand why... there was one thing i've maybe bad understand in the sekizai settings is the last step : "For Django versions after 1.10, add sekizai.context_processors.sekizai to your TEMPLATES['OPTIONS']['context_processors'] setting and use django.template.RequestContext when rendering your templates." where should i put "django.template.RequestContext" ? it the only way i have to solve my problem. i leave you few parts of my settings.py, thank's for help and answer Settings.py : """ Django settings for yufindRe project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from …