Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Been trying this for a while now. What else should I try?
getting this error when trying to run django-admin ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python310\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions. -
How to set the custom UserModel field value upon creation of the user in Django?
I have a custom UserModel which has a CharField named as pbc_id. I want it to be set as something like below: pbc_id = "PBC-" + str(user.pk) In other words, I want to attach the newly created user's primary key value at the end of the string "PBC-" and then assign this value to the pbc_id field. I have kind of done it, but it only work when I create a superuser using the terminal. But when I create a normal user using Django Administration Interface, it does not work and pbc-id gets empty value. My User model is below class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) pbc_id = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_candidate = models.BooleanField(default=False) is_voter = models.BooleanField(default=False) votes = models.IntegerField(default=0) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) My UserManager class is below: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email … -
Unable to Post comments to blog post with Django
I am creating a blog for a project and I am having problem getting my comments to post to the back end. My code is as follows: models.py from django.contrib.auth.models import User from products.models import Category class Post(models.Model): """Model to create blog posts""" author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=250) body = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): """Model to handle user comments""" author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.body[0:50] forms.py from .models import Post, Comment class PostForm(ModelForm): """ Form to allow site owner to create a new blog post """ class Meta: model = Post fields = ['category', 'title', 'body', 'image'] class CommentForm(ModelForm): """Form to handle user comments""" class Meta: model = Comment fields = ('body',) views.py def add_comment(request): """Method to add comments to a blog post""" post = get_object_or_404(Post, post_id) comments = post.comments.all() new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() template = 'blog/post_detail.html' context = … -
Django rosetta problem with changing translations
I am using django-rosetta for translations in my django project and have problem with changing translations using rosetta admin page. On the development environment everything works great. Problem appears on production server where django is run with gunicorn and it's probably related to cache settings in Django. So lets say i have a html file with translated string "Hello" displayed. Word "Hello" is translated to "Witaj", so when i open page in my local language i'll get displayed "Witaj". Then I change this translation to "Cześć" ("Witaj" -> "Cześć") and hit "Save and translate next block" button. Then there is an interesting part. When i reload this page on my local language settings i'll get displayed randomly one of "Witaj" or "Cześć". I've been reading about it and found something like that in rosetta docs Please make sure that a proper CACHES backend is configured in your Django settings if your Django app is being served in a multi-process environment, or the different server processes, serving subsequent requests, won’t find the storage data left by previous requests. and then TL;DR: if you run Django with gunicorn, mod-wsgi or other multi-process environment, the Django-default CACHES LocMemCache backend won’t suffice: use memcache … -
How do i create Model on Django
Create a Django model for People, Address, Doctor, Product, and Bio within any of your app. Use an appropriate database relationship, and create a relationship for the following models: People - Address People - Doctor People - Bio I'm pretty new to Django how do i go about this questions -
Referencing Attribute from Separate Class/Model
Using Django and PostgreSQL. I'm building a media streaming website. Where I have a Video class/model referencing back to a Broadcaster class/model. I'm attempting to grab an attribute (name) from the Broadcaster class and reference it as either the default value or directly from the ForeignKey relationship. Whenever I try to access/reference the attribute I get "<django.db.models.fields.related.ForeignKey>" Picture of ForeignKey Jargon when referencing Video model/class attribute broadcaster_name. (default=Broadcaster.name) BUT only when using broadcaster_name located in the Video class/model. Instead of the attribute reference of 'video.broadcaster.name', which is the goal. Below is my Python/Django code: ''' class Broadcaster(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50, unique=True, null=True) def __str__(self): return str(self.name) def get_name(self): return f'{self.name}' ''' ''' class Video(models.Model): broadcaster = models.ForeignKey(Broadcaster, on_delete=models.CASCADE, null=True) broadcaster_name = models.CharField(max_length=50, default=Broadcaster.name) ''' I've tried several different approaches with no avail... Below is my HTML/Django code: ''' {% for video in media_list %} <div class="card"> <img class="cover_img" src="{{ video.cover_img_url }}" alt="Cover Image"> <p></p> <h2>{{ video.title }}</h2> {# Works #} <h2>{{ video.broadcaster }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster.get_name }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster.name }}</h2> {# Doesn't Work #} <h2>{{ video.broadcaster_name }}</h2> {# Returns Object/ForeignKey Jargon #} </div> {% endfor %} ''' Similar … -
respond on post request to the third side, csrf token
I have two servers on Django, each server has its client. I need to send the request from one server to the second. I do it like this: def post(self, request, serial_number): if settings.DEBUG: setattr(request, '_dont_enforce_csrf_checks', True) charger_id = Charger.objects.get(serial_number=serial_number) form = WiFiConfigForm(request.POST) ip = charger_id.public_ip_address if form.is_valid(): data = {"wifi_ssid": request.POST.get('wifi_ssid'), "wifi_pass": request.POST.get('wifi_pass')} url = "http://127.0.0.1" + ":" + PORT + "/wifi_config/" + str(serial_number) + "/" client = requests.session() client.get(url) csrf_token = client.cookies['csrftoken'] payload = { 'csrfmiddlewaretoken': csrf_token } # response = requests.post(url, data=payload) # I tried this variant as well response = client.post(url, data=payload) print("response:", response) else: return Response("Form is not valid", status=status.HTTP_200_OK) return Response({"response": "response", "ip": ip, "serial_number": serial_number}, status=status.HTTP_200_OK) The problem is in csrf tokens, I don't know how to deal with them. The error is KeyError: "name='csrftoken', domain=None, path=None" -
reset form to initial data in invalid_form and display error in Django
I have a profile form that shows email, user name and first name. user only allowed to change first name field and the others are read only, if user change HTML value in email and username then submit it, it returns error but fill the fields with invalid value entered. I tried create a new instance of form and render it but it no longer shows the error. The thing I want is to reset invalid data then display the error. forms.py class UserEditForm(forms.ModelForm): email = forms.EmailField( label='Account email (can not be changed)', max_length=200, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 'form-email', 'readonly': 'readonly'})) user_name = forms.CharField( label='Username', min_length=4, max_length=50, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 'form-username', 'readonly': 'readonly'})) first_name = forms.CharField( label='First name', min_length=4, max_length=50, widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'Firstname', 'id': 'form-firstname'})) class Meta: model = UserBase fields = ('email', 'user_name', 'first_name',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user_name'].required = True self.fields['email'].required = True def clean_user_name(self): username = self.cleaned_data['user_name'] if username != self.instance.user_name: raise forms.ValidationError('Sorry, you can not change your username') return username def clean_email(self): email = self.cleaned_data['email'] if email != self.instance.email: raise forms.ValidationError('Sorry, you can not change your email') return email views.py class ChangeUserDetail(SuccessMessageMixin, LoginRequiredMixin, FormView): … -
Testing Updateview in Django won't update an object
I'm writing tests for my views and I'm stuck with the UpdateView and the POST request. For this simple test I try just to change first_name but assertion fails. What am I doing wrong? The test: class TestEmployeesUpdateView(TestCase): def setUp(self): self.test_user = User.objects.create_user( username='test_user', email= 'testuser@test.com', password='Testing12345') self.test_employee = Employee.objects.create( first_name='Bob', last_name='Smith', user=self.test_user, position='SM', birthday=date(year=1995, month=3, day=20), hire_date=date(year=2019, month=2, day=15), address='...', ) self.client = Client() def test_updateview_post(self): self.client.force_login(user=self.test_user) response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'frist_name': 'John'}) self.test_employee.refresh_from_db() self.assertEqual(self.test_employee.first_name, 'John') The view: class EmployeesUpdateView(LoginRequiredMixin, UpdateView): model = Employee template_name = 'employees/employee_details.html' form_class = EmployeeUpdateForm And the error: FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post self.assertEqual(self.test_employee.first_name, 'John') AssertionError: 'Bob' != 'John' - Bob + John -
how can i customize auto generated django form?
i've created a form on django app with its builtin forms class. here is my forms.py file. # import form class from django from dataclasses import field from django import forms from .models import #MYMODEL# class myForm(forms.ModelForm): class Meta: model = #MYMODEL# fields = "__all__" and my view function in views.py def index(request): context = {} form = myForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context['form'] = form return render(request, "index.html", context) and finally the page (index.html) that shows the form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Kaydet"> </form> So, what i need to do is to set custom input types like text or select box since the auto-generated form includes only text inputs. -
Uboundlocal error in django on my polls app on views. Py
From django. Shortcuts import get_object_or_404, render From django.http import HttpResponse def detail(request, question_id): Question = get_object_or_404(Question, pk=Question_id) return render(request, 'polls/detail.html', {'question':question } ) Full code: In my view.py -
Django custom login form validation with AJAX
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to validate a user's email and password in my login form... right now almost 100% of things work, for example, alert messages for mandatory inputs; however, from the Utils.py file if user "elif not object_user.allow_private_access:" validation is not working and, most importantly, validation is not checking user's password (also commented out in Utils.py). The "post" part in Views.py might have to be updated. I have included my custom Login form from Forms.py, Views.py (for Login page) and Utils.py (which does the validation and sends error messages to the front-end) and Urls.py. I did not add my AJAX because that is working well. Forms.py class UserLoginForm(forms.ModelForm): helper = FormHelper() helper.add_input(Submit('login_form_submit', numeratio_static_textLanguage['global_input_alert_maxCharacters_32'], css_class='global_component-button')) class Meta: model = CustomUser fields = ['email', 'password'] widgets = { 'email': forms.EmailInput(attrs={ 'maxlength': '256', 'style': 'text-transform: lowercase', 'id': 'input-email', 'class': 'global_component-input box'} ), 'password': forms.PasswordInput(attrs={ 'type': 'password', 'maxlength': '128', 'id': 'input-password', 'class': 'global_component-input box'} ) } def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.helper.form_action = '' self.helper.form_method = 'post' self.helper.form_id = 'login_form' self.helper.form_class = 'login_form' Views.py @csrf_exempt @anonymous_required(redirect_url='page__home') @require_http_methods(["GET", "POST"]) def view_userLogin(request, *args, **kwargs): template_name = '../frontend/templates/frontend/templates.user/template.page_login.html' form_class = UserLoginForm if … -
can't run a Django function from html template using ajax
I'm trying to run a Django function after a click event from user using Ajax inside a JS code in Django template HTML file. javascript block kml_layer.addListener('click', (kmlEvent) => { setMapOnAll(null); var clickedPoint = kmlEvent.latLng; newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng()) console.log("layer id is " + "{{ single_layer.id }}"); runKmOnSource("{{ single_layer.id }}", kmlEvent); //Here is where I called the ajax jquery function }); Ajax call function runKmOnSource(theID,kmlEvent,){ console.log("started ajax") $(document).ready(function () { $.ajax({ type: "POST", url: "{% url 'get_km_from_source' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', layer_id: theID, the_element_string_id: kmlEvent.featureData.id, clicked_lat: kmlEvent.latLng.lat, clicked_lng: kmlEvent.latLng.lng }, /* Passing the text data */ success: function (response) { console.log("ajax success"); kmOnSource.postMessage(response) } }); }); } urls.py path('get_km_from_source/', get_km_from_source, name='get_km_from_source'), and finally Django/python view def get_km_from_source(request): """ A function that takes data from the ajax function parsing it then ending back the result """ print("xxxxxxxxxxxxxxxxsssssssssss started kmonsource") #This line to test if function executed layer_id = request.POST['layer_id'] the_element_string_id = request.POST['the_element_string_id'] clicked_lat = request.POST['clicked_lat'] clicked_lng = request.POST['clicked_lng'] layer_object = models.MapLayers.objects.get(id=layer_id) print(f"layer object is {layer_object}") water_element_object = None nearest_cord = None first_cord = None last_cord = None for water_element in layer_object.waterelement_set.all(): if water_element.id_string == the_element_string_id: water_element_object = water_element break for single_cord in water_element_object.cordsforwaterelement_set.all(): if nearest_cord is None: … -
How to use foreign keys in django?
I can't seem to be able to use foreign key in django. I have a rental spaces network website that offers books. I've created a "Rental" model and a "Book" model and I've created a foreignkey for book model to be attached to a rental space. In admin panel everything works as it should, but I can't get it to show on website. I want to have several books in rental space 1 and none in rental space 2. I don't know how to manage it in views.py my models : class Rental (models.Model): rental_name=models.CharField(max_length=50) rental_number=models.IntegerField(default=0) rental_adress=models.CharField(max_length=100, default='') def __str__(self): return "{} {}".format(self.id, self.rental_name) class Book(models.Model): # autor, tytul gatunek, isbn, id w wypozyczalni book_author=models.CharField(max_length=50) book_title = models.CharField(max_length=100) book_isbn= models.CharField(max_length=17, unique=True) BOOK_GENRE= ( ('SF', "Sci-Fi"), ("ROM", "Romance"), ("HIS", "Historical"), ("HOR", "Horror"), ("THR", "Thriller"), ("BIO", "Biography"), ("KID", "For kids"), ("FAN", "Fantasy"), ) book_genre=models.CharField(max_length=3, choices=BOOK_GENRE) book_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1, related_name="display") class Meta: constraints =[ models.UniqueConstraint(fields=['book_author','book_title'], name='unique_book'), ] my views: class BookListView(ListView): model = Book template_name='book.html' class BookDetailView(DetailView): model = Book template_name='book_detail.html' class RentalListView(ListView): model = Rental template_name='rental_list.html' class RentalDetailView(DetailView): model = Rental template_name='rental_detail.html and my htmls look like this: <h1 style="font-size:11px; text-align:right;"><a href="{%url 'home' %}">Powrót do strony głównej</a></h1> {% block content %} {%for … -
JWT Tokens in Django Rest Framework
I am building a Django Rest Framework API which is using JWT authentication. I had created access tokens and refresh tokens and sent them to users. I also have a refresh token endpoint that will take old refresh token and generate new pair of tokens and send to user. I have doubt in its behavior related part. Currently what I can see that whenever I create new pair of access and refresh token using previous refresh token, the old access token is also working and new one is also working. However once when I was using OAuth2.0 (in different case), I observed that in that case the old access token won't work if we had created new refreshed tokens. But in case of my implementation of JWT in DRF this thing won't happens. I am not storing token in database. So I want to know that is this any implementation specific problem or is it the property of JWT only, and if it is property then please share some details over it with me. Thanks. -
How can i relaunch anaconda navigator without error
Navigator Error An unexpected error occurred on Navigator start-up Report Please report this issue in the anaconda issue tracker Main Error unacceptable character #x0000: special characters are not allowed in "C:\Users\Tokunbo.continuum\anaconda-client\config.yaml", position 0 Traceback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\exceptions.py", line 74, in exception_handler return_value = func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 137, in start_app window = run_app(splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 60, in run_app window = MainWindow(splash=splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window_init_.py", line 224, in init for _ in anaconda_solvers.POOL.solve(): File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\utils\anaconda_solvers\core.py", line 72, in solve configuration: typing.Any = binstar_client.utils.get_config() File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 250, in get_config file_configs = load_file_configs(SEARCH_PATH) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 242, in load_file_configs raw_data = collections.OrderedDict(kv for kv in itertools.chain.from_iterable(load_paths)) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 242, in raw_data = collections.OrderedDict(kv for kv in itertools.chain.from_iterable(load_paths)) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 222, in dir_yaml_loader yield filepath, load_config(filepath) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\config.py", line 206, in load_config data = yaml_load(fd) File "C:\ProgramData\Anaconda3\lib\site-packages\binstar_client\utils\yaml.py", line 12, in yaml_load return safe_load(stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml_init.py", line 125, in safe_load return load(stream, SafeLoader) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml_init_.py", line 79, in load loader = Loader(stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\loader.py", line 34, in init Reader.init(self, stream) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 85, in init self.determine_encoding() File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 135, in determine_encoding self.update(1) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 169, in update self.check_printable(data) File "C:\ProgramData\Anaconda3\lib\site-packages\yaml\reader.py", line 143, in check_printable … -
Why can't i see the text of description in my url?
In home category i have elf as a description : image I tried this code in my views to be able to display elf in my templates: def home(request ): p=get_object_or_404(category,pk=1) return render(request,'home.html',{'p':p}) and in templates i used this code <p id="id">{{p.description}}</p> to display it but it is not working i can not see the description or elf in this path path('',views.home), models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) urls: urlpatterns = [ path('api/', include(router.urls)), path('',views.home), path('admin/',admin.site.urls), ] Why can't i see the text of description in my url? -
GCP/Django - Server cannot serve a simple htmlresponse
So while I've successfully got the django app to locally serve and use the GCP SQL as backend, I'm having a hard time trying to get successful requests out of the django app using Google App Engine (Standard). Even a simple htmlresponse message doesn't work. Any advice here? Some odd things to note: there are 500 requests about the "favicon.ico" even though I don't use an ico file but a png. Removing the use of the favicon entirely yields similar results but now says "GET / HTTP/1.1 500" (Don't know what this is about) views.py (abbreviated) def index(request): return HttpResponse("Congratulations!") app.yaml runtime: python39 env_variables: BUCKET_NAME: "mystoragebucket" APPENGINE_URL: https://my-project-123456789101.uk.r.appspot.com/ handlers: - url: /static static_dir: static/ - url: /.* script: auto settings.py (abbreviated) DEBUG=False APPENGINE_URL = os.getenv('APPENGINE_URL') ALLOWED_HOSTS = [APPENGINE_URL[8:]] CSRF_TRUSTED_ORIGINS = [APPENGINE_URL] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True STATIC_URL = "https://storage.googleapis.com/mypublicstaticbucket/static/" SECRET_KEY = 'django-insecure-randomstringhere' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloud_sql/my-project-123456789101:us-east4:MYSQLInstanceNameHere', 'PORT' : 5432, 'NAME': 'MyDBNameHere', 'USER': 'myUsername', 'PASSWORD': 'MyPassword', } } -
Implementation of info in a web form
Im making a website for applying to jobs using django. The home page will display the different offers. I have 2 search bars, one for looking up a country or city and one for looking up job titles. The respective searches will come up. I want a drop down menu where you can pick a salary. The thing is when the person presses the salary i dont want a request to be sent just for the salary to be saved to a form. When a search is made I want both the salary and whatever is in the search bar to be sent to the backend -
how to authentication using react native and django
Hi I'm new to a react native I used to build full-stack pages using react js and Django in the backend but with react native I am facing a lot of problems with expo is there good documentation for that? -
Django '>' not supported between instances of 'NoneType' and 'int' Overlapping Checking
I am trying to make the code to check the overlapping in django forms , my code in form.py is , a = [] if count > 1: for i in range(count): first_number = self.data.get(f'newevent_set-{i}-first_number', []) last_number = self.data.get(f'newevent_set-{i}-last_number', []) new_run = self.data.getlist(f'newevent_set-{i}-new_run', []) a.append((i, first_number, last_number, new_run)) for i, base_data in enumerate(a): for check_data in a[i + 1:]: if float(base_data[1]) > float(check_data[0]): raise ValidationError ("Overlap Happening") -
How to stop scrapy from paginating the pages with repetitive records?
I tried to crawl a website whit pagination by scrapy, and it was ok! But, as this website gets update and new posts are added to this website, I need to run my code every day, so each time I run my code, it crawls all the pages. Fortunately, I'm using django and in my django model, I used unique=True So there are no duplicate records in my database, but I want to stop the pagination crawling as soon as it finds a duplicate record. how should I do this? here is my spider snippet code: def parse(self, response, **kwargs): next_page = response.xpath('//a[@class="next page-numbers"]/@href').get() news_links = response.xpath('//div[@class="content-column"]/div/article/div/div[1]/a/@href').getall() # print('*'*50) for link in news_links: yield scrapy.Request(url=link, callback=self.parse_item) if next_page: yield scrapy.Request(url=next_page, callback=self.parse) def parse_item(self, response): item = CryptocurrencyNewsItem() ... return item -
How to insert a variable from some premises created previously with the django query?
I'm building a query and I would like when the student is present and the justification is rejected that the value_x be placed, but the "Value" does not allow me to place a variable in it. Does anyone know a way to do this in django? Here's code below: inscritos = Inscricao.objects.all().annotate(valor_x=(Subquery(CursoValores.objects.filter(Q(curso__id_curso=OuterRef('Turma__Curso__id_curso'))&Q(data_inicio__lte=OuterRef('Turma__dt_hr_inicio'))&Q(data_fim__gte=OuterRef('Turma__dt_hr_inicio')) ).annotate(Max('valor')).values('valor__max'),output_field=FloatField())), valor_t=Case(When(Q(Presente=False)&Q(justificativa__situacao='I'), then=Value(valor_x)), default=Value(0), output_field=IntegerField(), ) -
Access to django filter data on view
I want to display information regarding the filter criteria received in the form, in the template. What is the best way to access this data in the view? -
Python subprocess doesn't find the PYTHONPATH
I'm using subprocess to call a python script but it doesn't work because it doesn't find my PYTHONPATH. I have a my PYTHONPATH put and it goes inside my folder. let's say my PYTHONPATH contains this path: /home/myproject. My architecture is this one: /myproject/djangoView/view_x.py from my view_x.py I use subprocess to launch a script that is on /myproject/scripts/script.py Then I start my server django, I have to click on a button and it should launch my script.py, to be clear it does work in local, but it doesn't work in preprod which is a server ubuntu. The error I have is ModuleNotFoundbecause in my script I call/utils/utils.py` So I just don't really understand why I have an error, my PYTHONPATH is set and correct, all the imports calling /utils/utils.py are working except when I'm using subprocess in my preprod server. I can't reproduce it in local. Is someone have an explanation for this behavior ? Here is my call: subprocess.run(["nohup python3 /home/myproject/scripts/script.py &"], shell=True) Thanx.