Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot find staticfiles
When I try to run my localhost server I get the following error: FileNotFoundError: [Errno 2] No such file or directory: '/static/CSV/ExtractedTweets.csv' This error is due to the line the line with open(staticfiles_storage.url('/CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile: This line of code can be found in a custom python module within my app folder. I have copies of /static/CSV/ExtractedTweets.csv in my project root folder, my app folder and in the folder enclosing my project root and app folders. I also have an additional copy of ExtractedTweets.csv within my app folder. My staticfile settings are configured as follows: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' It have placed the file in all possible locations yet django cannot seem to find it. If anyone has any idea how to resolve this error, please let me know. -
Как передать django forms все поля кроме одного?
У меня есть форма пользователя, и мне нужно в view передать все поля кроме пароля, как это сделать? -
Managing form state during navigation - Django
CONTEXT I'm working on an application with Django. I have to stick pretty close to an existing desktop app for it, which constraints the way I can build the user experience with forms. My issue is this. Say I have a form to fill in order to build a new Contract in the db. The "New Contract" page contains 5 tabs/pages in the original desktop app. 3 tabs can take inputs from users. The 2 other tabs contain related data the user might want to consult in order to fill out his form. Those 2 tabs may contain non-trivial amount of data. The "New Contract" form has an equivalent "Show Contract" page which has the same structure. That "Show Contract" page is implement as 5 different URL (e.g. 1 GET request for each, e.g. myapp/contracts/create/page1, myapp/contracts/create/page2, ...). I do not think that I can just build the html for the whole 5 tabs in a single request because of that. Otherwise building the whole thing, including the queries & rendering for the last 2 tabs takes too long, and most users would not necessarily need to refer to them anyways. WHAT I NEED Obviously, I do not expect a full … -
Django app CORS not working properly in production
this is my first time deploying django rest app. In the development i used CORS middle-ware to develop my front-end in reactjs. Now in production the CORS problem came back, and in the browser console i see thisconsole log. The problem is that the middle-ware still consider localhost, meanwhile the django app is running on remote server now. Anyone have an idea how to solve this ? Thanks ! -
Is there away of creating an end point for the Model Choices filed in Django rest framework
Hi I have a model in Django like this class MyModel(models.Model): CATEGORY = [ (1, 'Governments'), (2, 'Non Governments'), (3, 'Private Sector'), ] category = models.IntegerField(choices=CATEGORY, default=1 ) And to avoid having to change both the backend and frontend of the project every time I add a category I would like to have an endpoint that returns JSON of value and displays only these categories using the Django Rest Framework? result: [ { value:1, display:"Goverment" }, { value:1, display:"Non Gorverment" }, { value:1, display:"Private Sector" } ] Here is a serializer that I tried but I noticed Imay not be doing t the right way. class CategorySerializer(serializers.ModelSerializer): label = serializers.CharField(source='get_category_display') value = serializers.SerializerMethodField('get_value_number') def get_value_number(self, obj): return obj.category class Meta: models = myModel fields = ('value', 'label') -
Get value before template
How can i get input value after load template? i need to pass maquina value (not 189, need to pass {{qs.nombre}} or input value='maquina') before load template to run sentence sql. def show_trabajos(request): hostname = socket.gethostname() ip_add = socket.gethostbyname(hostname) qs = info_equipos.objects.all().filter(ip=ip_add) maquina= 189 codusuari = '161' ## sentencia = "exec [Empresa].[dbo].[PT_GET_ORDENES]" + str(maquina) + "," + codusuari cursor.execute(sentencia) results = namedtuplefetchall(cursor) <fieldset class="scheduler-border"> <legend class="scheduler-border">EMPLEADO</legend> <b><p class="black">IDENTIFICADO: </b><input class="sinborde" type="text" name="empleado" value="{{ user.username }}" readonly /></p></p> <b><p class="black">EMPLEADO: </b><input class="sinborde" type="text" name="empleado" value="{{ user.first_name }} {{ user.last_name }}" readonly /></p> <b><p class="black">IP: </b><input class="sinborde" type="text" name="ip" value="{{ qs.ip }}" readonly /></p> <b><p class="black">M&Aacute;QUINA: </b><input class="sinborde" type="text" name="maquina" value="{{ qs.nombre }}" readonly /></p> <b><p class="black">Nº M&Aacute;QUINA: </b><input class="sinborde" type="text" name="rec_sistrade" value="{{ qs.rec_sistrade }}" readonly /></p> <b><p class="black">USUARIO SITRADE: </b><input type="text" class="sinborde" name="user_sistrade" value="{{ user.user_sistrade }}" readonly /></p> </fieldset> -
Django left join (only two models)
I'm stack on it, please need your help. I have two models and a want to select all (or filtered) fields from Channel and left join last_published video from Video model. Need good solution using django ORM. class Channel(models.Model): name = models.CharField(max_length=150, blank=False, null=False) url = models.CharField(max_length=100, blank=False, null=False) def __str__(self): return self.name class Video(models.Model): channel = models.ForeignKey(Channel, on_delete=models.CASCADE) title = models.CharField(max_length=150, blank=False, null=False) url = models.CharField(max_length=50, blank=False, null=False, unique=True) publish_date = models.DateTimeField(blank=True, null=True, auto_created=False) embedurl = models.CharField(max_length=50, blank=True, null=True, unique=True) def __str__(self): return self.title -
Why am I getting error 404 on my django server?
I'm trying to test my django app on production server but static files are not found. I spent many hours trying to solve this issue but ended up with nothing. So, in settings.py I have this: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Then I put all static files in a folder named 'static' in django project folder and I did python manage.py collectstatic, I got a warning that files will be overwritten then I confirmed this and files were successfully copied but i keep getting error 404. I tried adding static path to urls like this: urlpatterns = [] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) But it did nothing. -
How to run scrapy spider with celery
I'm trying to run a scrapy spider which takes some argument and runing it with os.system. But the celery task(scraper) doesn't gets executed untill it finishes. Spider class SpecificAuthorQuotesSpider(scrapy.Spider): """Extracts the quotes from specific author""" start_urls = ['https://quotes.toscrape.com/'] name = "some-quotes" def __init__(self, author=None, **kwargs): self.author = author super().__init__(**kwargs) def parse(self, response, **kwargs): item = QuotesItem() all_div_quotes = response.css('div.quote') for quote in all_div_quotes: title = quote.css('span.text::text').extract_first().replace('”', '').replace("“", "") author = quote.css('.author::text').extract_first() # Check if author's name matches if author.strip().lower() == self.author.strip().lower(): item['text'] = title item['author'] = author yield item # Crawl Next Page next_page = response.css('li.next a::attr(href)').get() if next_page is not None: yield response.follow(next_page, callback=self.parse) Task @shared_task def task_scrape_from_author(author_name): """Scrape quotes from author""" django_path = Path(__file__).resolve().parent.parent os.chdir(str(django_path)+"/scraper") os.system( "scrapy crawl some-quotes -a author='{}'".format(author_name)) View def scrape_quotes_from_author(request): if request.user.is_superuser: author_name = request.POST.get("athr_name") task_scrape_from_author.delay(author_name) messages.add_message( request, messages.INFO, 'Started crawling quotes from {}'.format(author_name)) return HttpResponseRedirect(reverse("admin:index")) else: return HttpResponseRedirect("../") I don't understand why is the task not getting completed and interrupted with any messages. I tried setting max timeout also but that din't worked. -
Django form.is_valid returns false for valid email
I am grabbing the user's entered email and using form.is_valid(). It returns False, I checked with the django shell validation for email, and it returns Invalid emailfor every email I could think of. For ex. test@gmail.com. How can I make the email pass the form.is_valid()? #forms.py class SendEmailForm(forms.Form): to = forms.CharField() subject = forms.EmailField() content = forms.CharField(widget=forms.Textarea) class Meta: fields = ['to', 'subject', 'content'] #views.py def home_view(request): print(f'Logged in as {request.user.username}') if request.method == 'POST': form = SendEmailForm(data=request.POST) if form.is_valid(): # returns False for any email print('ok') print(request.POST) else: print('not ok') print(request.POST) -
Problems Unit Testing Django Code which uses ThreadPoolExecutor
I'm writing unit test cases for some django code which is using the ThreadPoolExecutors executor.map function to map a function which makes calls to the database while testing the code there is a problem while tearing down the database OK Destroying test database for alias 'default'... C:\Users\KaushalKulkarni\Desktop\Python\guidance\venv\lib\site-packages\django\db\backends\postgresql\base.py:304: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "C:\Users\KaushalKulkarni\Desktop\Python\guidance\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.ObjectInUse: database "test_guidance" is being accessed by other users DETAIL: There is 1 other session using the database. any tips on how to test this code without getting errors -
How to add tags when add a page to a known parent programatically in wagtail?
I would like to create programatically a sub page for a known parent. here is the code. parent_page = Page.objects.get(title='index02').specific news_page = BlogPage( title = 'title test 08', slug = 'title_test_08', body='Something pleasant to hear.', intro="desc", ) parent_page.add_child(instance=news_page) news_page.save() It works, but I added tags = '[tag01,tag02]' in news_page , It failed to add tags, Could sb tell me how to add tags? thanks. -
help_text - Django Crispy Forms
I want to add help text to the form: investigation_title = forms.CharField( error_messages={'required': 'Please provide an Investigation Title'}, help_text = 'Help text...', ) def __init__(self, *args, **kwargs): super(InvestigationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' ... self.helper.help_text_inline = True ... But like this the help text is render below the field box. How to move the help text to the right side of the field box, position as it shows in the picture in the red rectangle? -
Django. How to save serialized and validated data?
I have a Car model with name, model and serial number fields. In which the combination of the name and model fields must be unique. I am using serializers.ModelSerializer from rest_framework and validator UniqueTogetherValidator. validators = [ UniqueTogetherValidator( queryset=models.Car.objects.all(), fields=['name', 'model'] ) ] The database already has an entry {'name': 'one', 'model': '13', 'serial number': 99}. I want to add a list of cars: data = [{'name': 'one', 'model': '13', 'serial number': 99}, {'name': 'two', 'model': '3', 'serial number ': 98}, {' name ':' three ',' model ':' 1 ',' serial number ': 949}] For this I use: serializer = CarSerializer (data = data) if serializer.is_valid (): serializer.save () I understand that is_valid () will return False. In the passed list, only one record is not valid, how to save valid data from the passed list? -
django "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to save a M2M object ( set it to a default value which is the one with id = 1 ). The problem I'm getting the following error: "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used. I looked at previous feeds that covered the same error but no one explained when it happens in the form_valid function as it happened to me My code is as follows : def form_valid(self,form): instance = form.instance instance.groups.set(1) instance.save() return super(UserCreateView,self).form_valid(form) -
Simplest way to lock the model instances and its related object in Django
To avoid the concurrency I am trying to put a lock on Django's model's instances. Orders class Orders(BaseModel): created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Properties, on_delete=models.PROTECT, null=False, blank=False) units = models.IntegerField(null=False, blank=False) buy_price_per_unit = models.FloatField(null=True, blank=True) sell_price_per_unit = models.FloatField(null=True, blank=True) order_type = models.ForeignKey(OrderType, on_delete=models.PROTECT, null=False, blank=False) order_status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, null=False, blank=False) fluctuation_upper_limit = models.FloatField( null=False, blank=False) #IN PERCENT fluctuation_lower_limit = models.FloatField( null=False, blank=False) #IN PERCENT order_trade_fee = models.FloatField( null=False, blank=False) #IN PERCENT tax_percent = models.FloatField( null=False, blank=False) #IN PERCEN In the above model I have a ForeignKey field property referencing to the model Properties. Furthermore, I also have a model PropertyOwners which has a ForeignKey field property referencing to the model Properties. The query I am using is - Orders.objects .select_for_update() .exclude(created_by=created_by) .values('id', 'property', 'units', 'created_by', 'sell_price_per_unit', 'order_status') .filter(property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price) .order_by('sell_price_per_unit') You can see I have used select_for_update() to lock the Orders instances fetched by this query. However, I also want to lock the instance of model Properties to which all these order are pointing and the instances of the PropertyOwners where the field property and created_by from Orders is equal to the fields property and owner from PropertyOwners for each order. The query … -
Integrating Django Rest Framework with OneLogin
I am working on a backend built on Django and Django Rest Framework. I have been trying to integrate with Onelogin for a little bit and I do not manage to do it. SAML: It seems that python3-saml is mainly build for traditional Django using sessions. Which is not a very REST like behavior. I could not find a way to make it work with DRF. Nor could I find a package that fits my needs. I will continue working on OpenId connect but I am wondering if it is possible to use Django Rest Framework with python3-saml? Thank you for you help -
mixins Django how to enable staff-user post, edit, delete permission in html template
I am using mixins in my views for restrict unauthenticated user to access my blog-post page, edit-page and delete-page. Right now only admin user can access those page but I also give permission to staff user for access those page. see the picture: still now my staff user get 404 error when trying to access those page. here is my code: #views.py class blog_publish_view(PermissionRequiredMixin,CreateView): raise_exception = True permission_required = "blog_add_blog" model = Post form_class = BlogPost template_name = "blog_post.html" #fields = ['title','author','body'] class blog_update_view(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog_change_blog" model = Post template_name = "blog_update_post.html" form_class = BlogPost class blog_delete_view(PermissionRequiredMixin,DeleteView): raise_exception = True permission_required = "blog_delete_blog" model = Post template_name = "delete_blog_post.html" success_url = reverse_lazy('blog') #my html page for post blog: {% if user.is_authenticated %} <div class="container"> <h1>Publish Blog</h1> <form method="POST"> {% csrf_token %} {{form.media}} {{form.as_p}} <button class="btn btn-info">Publish</button> </form> </div> {% endif %} my staff user can post,edit,publish blog from django admin panel but how to enable those permission in html template. -
requests python in Django ASGI server
I am using Django ASGI server and am sending a post request but its not responding. Continuously displaying "sending request" in postman My views.py @csrf_exempt def test(Request): if Request.method == "POST": requests.post('http://localhost:8000/api/token/') return HttpResponse(response) My urls.py urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This request is fine This request is not working -
WebDriver Execution Denied permission error on Cpanel
Hello I am using Chrome web driver for automation process. This Script Extract data from different websites. Everything is working fine on my local host but On deployment it Throwing permission error in execution. i have change the Permissions but still getting the same error... Can anyone help me in this options = webdriver.ChromeOptions() options.add_argument("headless") driver = webdriver.Chrome(executable_path="payviacoins.xtradehub.com",chrome_options=options) ERROR Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home -
Saving cookies via Python HTTP class
I have an extrenal authentication web application which isn't a part of my base web app. I would like to save auth token after succesfully login process into my main app. The only one available method is using BE for that. We have a PY/Django on BE. I was considering to use HTTP class with .set_cookie method to do that, but Im afraid about secure aspect of that process. Is using BE to save a cookies by HTTP class is safe? Is there any chance to malform/compromise that process from outside? -
Django Rest Framework: Multiple branches of API w/ varying queryset/permissions
In my Django-Rest-Framework application, I have the need to divide the API into two branches such as: /api/public/... /api/private/... Consider a model Analysis like so: from django.db import models from django.conf import settings class Analysis(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) public = models.BooleanField(default=True) What I want then is: /api/public/analysis => filter queryset with Q(public=True) /api/private/analysis => filter queryset with Q(user=request.user) | Q(public=False) Similar pattern is required in 5+ models. I have thought of 2 half-baked solutions: 1. AbstractViewSet sub-classed into PublicViewSet and PrivateViewSet class AbstractAnalysisViewSet(viewsets.ReadOnlyModelViewSet): queryset = Analysis.objects.all() serializer_class = AnalysisSerializer ordering = [ "-created_at", ] permission_classes = [IsAuthenticated,] class PrivateAnalysisViewSet(AbstractAnalysisViewSet): def get_permissions(self): permissions = super(PrivateAnalysisViewSet, self).get_permissions() if self.action in ["retrieve"]: permissions.append(HasObjectPermission()) return permissions def get_queryset(self): queryset = super(PrivateAnalysisViewSet, self).get_queryset() if self.action in ["list"]: auth_user = self.request.user query = Q(user=auth_user) | Q(public=False) queryset = queryset.filter(query) return queryset class PublicAnalysisViewSet(AbstractAnalysisViewSet): def get_permissions(self): permissions = super(PublicAnalysisViewSet, self).get_permissions() if self.action in ["retrieve"]: permissions.append(IsPublicObjectPermission()) return permissions def get_queryset(self): queryset = super(PublicAnalysisViewSet, self).get_queryset() if self.action in ["list"]: query = Q(public=True) queryset = queryset.filter(query) return queryset This would work but I don't really want to duplicate views into multiple classes like that because then I also need to register multiple viewsets with the DRF router. As I … -
Store HTML field data after refresh
I am building a BlogApp and I am trying to implement city model field in template. I am accessing and saving using field in template input method using :- <input data-city-picker="true" name='city'>. BUT When i write city and save it then it is successfully saving in DataBase BUT when i refresh the page then city name automatically disappear from the field BUT when i check on admin section then city is showing successfully BUT choosen city name in not in the text area anymore. views.py def edit_location(request): if request.method == 'POST': location_form = EditLocation(request.POST, request.FILES, instance=request.user.profile) if location_form.is_valid(): custom_form = location_form.save(False) custom_form.save() messages.success(request,"Location Saved") return redirect('profile') else: location_form = EditLocation(instance=request.user.profile) context = {'location_form':location_form} return render(request, 'edit_city.html', context) edit_city.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <input data-city-picker="true" name='city'> </textarea> </table> <button type="submit">Save Changes</button> </form> </div> I know i can also access the model's city field using {{ location_form.city }} BUT using this way i will not be able to access city's choice library. AND the city is successfully showing when i access city name BUT whenever i try to edit city name then city name is not in the textarea. I have no idea, What am i doing … -
How I can get the pk in the home view www.mywebsite.com
I tried to get the pk from this function def home_view(request, pk): but because this in home view www.site.com it return error home_view() missing 1 required positional argument: 'pk' so it is didn't worked with me My qustion is how I can pass pk to the template that in website domain without any extra urls like this www.site.com My view def home_screen_view(request, pk, *args, **kwargs): post= Post.objects.filter(pk=pk) #here I want to get the pk comment = PostCommentIDF.objects.filter(post=post) return render(request, 'personal/home.html', {'comment': comment) -
Django - automate CRUD from models (DRY approach)?
I am new to Django but not to developing. I need to make an application in which user can do CRUD operations (Create, Read, Update, Delete). This functionality should apply to all models and the fields for Create & Update will be auto-generated from model attributes. What I describe is pretty much the functionality that comes with the Admin page. However, I want to use it in my own app instead of using the Admin app. For example, let's suppose we have Author and Book models: (models.py) from django.db import models class Author(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) def __str__(self): return self.last_name class Book(models.Model): title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title I suppose that the above information (models) could be enough for CRUD operations, without repeating code of the same logic for each model. I am aiming at a functionality like in admin page where all you have to do is register your model. I am aware of ModelForm and Generic Views but while they help avoiding hard-coding form fields, I have not found a non-repetitive coding approach. I would like to avoid approaches like the following where same code is being duplicated for each …