Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Working with multiple input forms in Django
I'm working on a web app that allows users to critically appraise medical articles. The common entry into the user input is entering a PubMed url and an article type (publication_type, e.g. cohort, RCT, etc). There are 10 types of article they could choose, and each will have different required input fields. My question is: there being so many input forms and associated fields, how is it best to split this up? For example, as a beginner my first thought was to define all of the input fields in same model class, and display the input form and output using {% if publication_type == .....%}, {% elif .... %}, etc, but I wondered if there is a better way of doing it? Another way might be to create different models for each with ForeignKeys, but wouldn't that get a bit messy? Hope that makes sense? Thanks in advance -
return a list of file_id based on some list of file_type provided
so I was trying to find the best way to return a list of file_id. file_id is basically the uuid or the primary key of the file. Now i have new_file_type = 'google' and old_file_type = ['google', 'linkdin', 'twitter']. Note that the only difference between new_file_type andn old_file_type is new_file_type is a string and old_file_type is a list contains more than one items. So i have the following implementation which returns the list of file_id based on the job_id and the new_file_type. Now how could i go with the old_file_type, i know , i have to loop. But how to go efficiently ? def fetch_file_meta(job_id=None,new_file_type =None,old_file_types=[], **kwargs) -> list: """Fetch file meta data if to run batch files process. :param job_id: job id to merge files :param kwargs: :return: <list> a file ids to be merged into one file and the job meta """ LOGGER.info(f"fetch files for job: {job_id}") file_data = None job_meta = {} file_id_list = [] file_store_url = f"{FILESTORE_PATH}/attributes/attributes/" if job_id: cleaned_filter_params = {'meta__job_id': job_id, 'file_type': new_file_type} LOGGER.info(f"cleaned filter params: {cleaned_filter_params}") for old_file_types in old_file_types: try: response = old_file_types.requests.get(file_store_url, params=cleaned_filter_params) filestore_file_meta_response = old_file_types.response.text LOGGER.info(filestore_file_meta_response) # can retrieve multiple files, just use the first index. old_file_types.file_data = json.loads(filestore_file_meta_response) LOGGER.info(f"file_data: … -
Django: `RunPython` outside of migration?
The RunPython runs code in historical context, that is, recreating the model classes as they were at the time of the migration. Can that command be used outside of a migration script? That is, is it possible in some external script, to write something like RunPython(migration_number=12, forward_code, reverse_code) -
How to modify the form filed data based on another field?
I have a model: class PastStudy(Model): grade_average = FloatField(null=True) I have a modelform as below: class PastStudyForm(ModelForm): class Meta: model = PastStudy fields = ('grade_average', ) What I have in view: if request.POST: past_study_form = PastStudyForm(request.POST) if past_study_form.is_valid(): return HttpResponse(past_study_form.cleaned_data['grade_average']) What I need is that I want to write a clean method for PastStudyForm so that in case I entered 90 as grade average, HttpResponse converts it two 0-20 grading scheme and returns 18. I tried this and I was still getting 90 not 18 class PastStudyForm(ModelForm): class Meta: model = PastStudy fields = ('grade_average', ) def clean(self): cleaned_data = super().clean() grade_average = self.cleaned_data['grade_average'] self.cleaned_data['grade_average'] = grade_average/20 return cleaned_data However, I still get 90. I also have tried a few other methods but I still was getting 90 in HttpResponse The real code is huge and I have summarized it in here and other aspects of the problem are not explained in here. That is why I prefer and expect to get a response in which I am advised how to it in the form definition, not other methods such as converting it in the view. -
How can i confirm a database entry in django admin?
I have been working around this problem. I have a user submitting a HTML form lets say to list their hotel on my website. I need to review this form before i add it into my hotels model to be published. One approach i have worked on is to use a requests model where this form can be stored and later using django admin action write a custom action to add/remove the request. In case of acceptance i copy the details to my hotels model else it sends an email or a notification back to user. Second approach is simply using django action on hotels model where the request is sent to approve it or reject it. In this case i want to know if thats possible where a data point doesn't get written to database until it's been accepted by admin. If yes how can i do that? Finally, these details are displayed on my main page and search page for users to book these places. If there is a better and effective way to do it. Please share that. Thanks in advance. If something isn't clear i can answer your specific questions in the comments below 😊. Have … -
Validate pk as int in drf viewset retrieve url
Code looks as follows: class UserViewSet(ViewSet): # ... Many other actions def list(self): # list implementation def retrieve(self, request, pk): # manual pk int validation router = DefaultRouter() router.register(r"users", UserViewSet, basename="users") urlpatterns = router.urls Right now pk is not validated as int therefore a request to db is made, which I want to avoid. Is there any way I can add that type of validation in urls? I can achieve that without using router like this: urlpatterns = [ url(r'^users/(?P<pk>\d+)/$', UserViewSet.as_view({'get': 'retrieve'}), # many other actions have to be added seperately ] But I have many actions in my viewset and all of them have to be added separately. Is there a cleaner way to do so or a package? -
Where can I find all the django's curly brackets functions?
I'm working with django and I'm new in it. I would like to know where I can find a list of all the {} function please ? like {% if user.is_authenticated %} and all of them ? Thanks, -
Make custom form manually in Django based on a model
I am making a basic attendance record system with following models in my models.py file : Department, Employee, Absence. Absence model is as below: class Absences(models.Model): emp_id = models.ForeignKey(Employees, on_delete=models.CASCADE, null=False) leave_date = models.DateField(null=False) leave_type = models.ForeignKey(LeaveTypes, on_delete=models.CASCADE) absence_added = models.DateTimeField(auto_now_add=True) absence_updated = models.DateTimeField(auto_now=True) Now I want to create a form that lets you select date (that will be inserted in leave_date column) and a list of all employees with a dropdown (populated with leave_type) and submit button (which once clicked with save absences to database based on Absences model above. How do I do this? -
Django Heroku users_customuser table can't migrate
I have a Django project I've been developing locally for a while. It works fine on my local machine, and I am using a customuser setup so that my login auth only needs email / password, as opposed to the default Django user table which needs email / username / password. I just got my project hosted on Heroku, and can see the webpage UI get loaded fine. But I'm getting Django errors when clicking any links, and think its connected to an issue when I try to run heroku run python manage.py migrate I'm trying to run this on heroku to setup the DB, but when I do so I get an error saying: Running python manage.py migrate on ⬢ songsweeper... up, run.1353 (Free) Operations to perform: Apply all migrations: account, admin, auth, contenttypes, playlist, sessions, sites Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", … -
non_field_errors, Invalid data. DRF
when I post nested serializers in Postman it gives me following error "profile": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } but when I make the GET request it shows like that "email": null, "phone_number": null, "profile": { "first_name": "Jane", "last_name": "Doe", "interestlist_set": [ { "interest_list": [ 2, 1 ], "user": 1, "category": 1 } ] and I am posting as the same as above one more thing here interest_list is ManyToManyField it may be problem but I cannot solve this here is my model models.py class InterestName(TimeModel): name = models.CharField(max_length=255) class InterestList(models.Model): interest_list = models.ManyToManyField(InterestName) user = models.ForeignKey(Profile, on_delete=models.CASCADE) category = models.ForeignKey(ListOfInterestCategory, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) serializers.py class ProfileSerializer(serializers.ModelSerializer): interestlist_set = InterestListSerializer(many=True) class Meta: model = Profile fields = ['first_name', 'last_name', 'interestlist_set',] class UserRegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = CustomUser fields = ['email', 'phone_number','profile'] def create(self, validated_data): profiles_data = validated_data.pop('profile') user = CustomUser.objects.create(**validated_data) for profile_data in profiles_data: Profile.objects.create(user=user, **profile_data) return user here what I have tried so far I cannot make POST request in Postman how can I solve this issue? Thanks in advance! -
date-format not working on html page with datepicker
First, I'm relatively new to Django. I've seen my question addressed here with answers that I've tried to implement without success. Using a date picker that formats the date differently then how its stored and returned on the form initially. forms.py .... start_date = forms.Datefield(widget=forms.DateInput(format='%m/%d/%Y'), input_formats=['%m/%d/%Y']) queries.html .... <div class="col-4"> <label for="start_date" style="font-weight: bold;">Start Date</label> <div class="input-group date" data-provide="datepicker"> <input type="text" name="start_date" id="start_date" value="{{queryform.start_date.value}}" class="form-control"> <div class="input-group-addon"><span class="glyphicon glyphicon-th"></span></div> </div> </div> .... <form method="post"> {% csrf_token %} <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, dateFormat: 'mm/dd/yyyy', changeYear: true, yearRange: "2010:2025" }); }); </script> url.py path('editqueries/<id>', views.editqueries, name='editqueries'), views.py def editqueries(request, id): query_data = get_object_or_404(Query, pk=id) if request.method == "POST": query_form = QueryForm(request.POST, instance=query_data) if query_form.is_valid(): the_query_name = query_form.cleaned_data["query_name"] # get the hidden field from the html page (but not on the # Django form) current_query_name = request.POST["currentqueryname"] # test to be sure if the names are not the same that changing # the name doesn't create a duplicate query_name if not the_query_name == current_query_name: try: test_query = Query.objects.get(query_name=the_query_name) except Query.DoesNotExist: # this is allowed. Named changed does not create a # duplicate query_form.save() query = Query.objects.all() query_flag = "None" context = {'queries': query, 'query_flag': query_flag} return render(request, 'seakerUI/queries.html', context) … -
Why JSON.stringify() return undefined and produce auth.js:65 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined?
I'm trying to login in my django application using axois and react-redux. My problem is when I entered wrong login information then the LOGIN_FAIL action is work fine but when entered correct login information the LOGIN_SUCCESS action is not work and produce the following error "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined". I have debugged my code and this line const body = JSON.stringify({ username, password }); returns undefined even username and password data is successfully received. Is the problem happened this reason? I am confused!! I have also tried to login using postman and it's working fine. How can I solve this problem? Can anyone solve my problem? Thanks in advance. Here is my action code: import axios from "axios"; import { errorMessage } from "./messages"; import { USER_LOADING, USER_LOADED, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL } from "./types"; // Login User export const login = (username, password) => dispatch => { // Headers const config = { headers: { "content-type": "application/json" } } // Request body const body = JSON.stringify({ username, password }); axios.post("/api/auth/login", body, config) .then(res => { dispatch({ action: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { dispatch(errorMessage(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL }); }); } Here is … -
How to show ForeignKey obj name on add data admin mode
How to show detail about foreignkey link pic : https://sv1.picz.in.th/images/2019/08/05/KLGvi9.png and my code in below. class Address(models.Model): line1 = models.CharField(max_length=150) line2 = models.CharField(max_length=150) postalcode = models.CharField(max_length=10) city = models.CharField(max_length=150) country = models.CharField(max_length=150) class Anniversary(models.Model): date = models.DateField() class Person(models.Model): name = models.CharField(max_length=50) birthday = models.DateField() anniversary = models.ForeignKey(Anniversary, on_delete=models.CASCADE) address = models.ForeignKey( Address, on_delete=models.CASCADE) -
How to run third party js script in Django / run client side js in server side
In my current project I have an external js script, which have some methods, I can access these methods, I also pass data to those methods & they give me output as well. Normally it works in client side. Now I am trying to do the same process in server side. For example: I've an js file which have some methods to change format of an image, I will give the image file and the expected image format as parameter then the method returns the output image. Where the process works in client side. Now I'm trying to make an REST api by using django. How can I solve my problem.. ?? Please help me. Any type of help will be appreciated. Thanks -
Why is my txt file not exporting with newlines properly?
I know how to make and read from txt files in python, but it's not working properly when I do it as an HttpResponse in django. def abc(request): users = User.objects.all() filename = "my-file.txt" text_string = '' for user in users: text_string += '{} {}\n'.format(user.id, user.username) print(text_string) # prints properly in the terminal with a new line response = HttpResponse(text_string, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response This file downloads just fine, but the content looks like this when opened: 1 userA2 userB3 userC But I am expecting it to look like: 1 userA 2 userB 3 userC Another odd thing I noticed is when I copy / paste the contents in this text editor, it retains the new lines I'm expecting, but is not displaying it as I want in the file. -
Trying to prevent international users from accessing my Django site
I don't want to have a cookie policy, so for legal issues, I want to block international users from my site - basically redirect them to a "sorry not available to international users page" and prevent them from accessing the main site. How should do I prevent them from accessing the main site? There is no authentication system for the main site currently. This is mostly a design question. This is how I thought about doing it, but it would be hard. Is there an easier way? First, I pull their country from their IP (which I already have). Then, I force them into a first level login page, that they need a username and password to login. However, this is painful, since I already have a user authentication system for paying users. Is there a better way to do this? -
How to exclude querysets that already has m2m relationship
I'm creating a Model with a many2many relationship, if the other model has a parent it needs to be excluded from the form I know how to exclude if I know the pk but it has to be for any relationship, I read the django official documentation and can't solve it yet models.py: `class Invoice(models.Model): invoice_created = models.DateField(auto_now_add=True,verbose_name='Date_limit') class GlobalInvoice(models.Model): date_limit = models.DateField( auto_now_add=True, verbose_name='Date Limit' ) invoices = models.ManyToManyField( Invoice, verbose_name='Invoices' )` forms.py `class GlobalInvoiceForm(forms.ModelForm): def __init__(self, *args, **kwargs): invoices = Invoice.objects.filter( invoice_created__lte=date.today() ) # the exclude should be here super(GlobalInvoiceForm, self).__init__(*args,**kwargs) self.fields['invoices'] = forms.ModelMultipleChoiceField( label='Invoices:', widget=forms.CheckboxSelectMultiple, queryset=invoices ) class Meta: model = GlobalInvoice fields = '__all__' ` If I create a new Global Invoice the Invoice field needs to exclude the Invoices that already has a Global Invoice assigned -
Display radio button with dropdown user selection
I would like to create two fields: a radio button and dropdown radio button will populate given choice and dropdown will pull from the DB. Getting stuck with displaying the radio and fetching value Should I be using modelform or form? I would like to store data in DB when radio button selection is down with dropdown value and like to take that value to display a case types. MODEL.py class Selections(models.Model): roletype = models.CharField(max_length=8, default=None) LOCATIONS = (('DC1','DC1'), ('DC2', 'DC2'), ('DC3', 'DC3')) location = models.CharField(max_length=4, choices=LOCATIONS) def __str__(self): return self.roletype FORMs.py from django import forms from .models import Selections class SelectionsForm(forms.ModelForm): ROLES = (('1','Type1'),('2','Type2'),('3', 'Type3')) roletype = forms.ChoiceField(choices=ROLES, widget=forms.RadioSelect) class Meta: model = Selections fields = ['roletype','location'] VIEWs.py ## VIEW: Populate dropdown to select Data center def get_role_dc_data(request, *args, **kwargs): location = Midtier.objects.get(id=0) # List of objects roletype = Midtier.objects.get(id=1) # List of objects context = { 'location': location, 'roletype': roletype } return render(request, 'selections/view.html', context) view.html <th> {% for radio_input in context.roletype %} <input type="radio" name="choice" id="{{ radio_input.id }}" value="{{ radio_input.id }}"> {% endfor %} </th> <th> <div class="fieldWrapper" align="center" id="mainselection"> <select name="location"> <option selected="selected">Select an the site</option> {% for instance in context.location %} <option >{{ instance.location }}</option> … -
Python 3.6.4 - Having problems installing mysqlclient?
I am trying to install mysqlclient with the pip command but for some reason it just doesn't work. I am running this on a macOS. Python 3.6.4 Django 2.1.5 I have seen the question here Unable to install mysqlclient in python3 virtualenv but none of the answers are any useful. I am also aware of some of the issues affecting macOS as mentioned here https://pypi.org/project/mysqlclient/ but I don't think my error is to do with that. Here are the error logs ERROR: Command errored out with exit status 1: command: /Users/azky/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/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/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-wheel-a12yp4ks --python-tag cp36 cwd: /private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.6-intel-3.6 copying _mysql_exceptions.py -> build/lib.macosx-10.6-intel-3.6 creating build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb creating build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.6-intel-3.6 /usr/bin/clang -fno-strict-aliasing … -
When I have 100 columns, what should I do to retrieve the columns?
Hello I have a question for django orm ~! table model is this author | ca1 | ca2 | ca3 | ca4 | ca5 | ca6 | … | ca100 mike | rabbit | bird | shark| mouse | dog | cat | When I search using the search term tiger To get the next search result mike, ca5, dog What should I do with orm? thank you for let me know~! -
How could I change a Boolean field to show a value like Up = true or Down = False in a serialized field in Django
I have a serialized data set in Django Rest Framework to be consumed, but I have a question that I want to solve, there is a field that is Boolean, and clearly when I serialize it shows two values: true or false, the question is that I do not want show these values, I want to show UP = True, DOWN = False These fields in question are: status and ospf My Model class Interfaces(models.Model): id_interface = models.PositiveIntegerField(primary_key=True) id_EquipoOrigen = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_origen') id_PuertoOrigen = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_origen', null=True, blank=True) estatus = models.BooleanField(default=False) etiqueta_prtg = models.CharField(max_length=80, null=True, blank=True) grupo = models.PositiveSmallIntegerField(default=0, blank=True) if_index = models.PositiveIntegerField(default=0, blank=True) bw = models.PositiveSmallIntegerField(default=0, blank=True) bw_al = models.PositiveSmallIntegerField(default=0, blank=True) id_prtg = models.PositiveSmallIntegerField(default=0, blank=True) ospf = models.BooleanField(default=False) description = models.CharField(max_length=200, null=True, blank=True) id_EquipoDestino = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_destino') id_PuertoDestino = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_destino') ultima_actualizacion = models.DateTimeField(auto_now=True) My Serializers Model Interfaces class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class InterfacesViewSet(viewsets.ModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer pagination_class = PostPageNumberPagination filter_class = InterfacesFilter -
How to Execute an Asynchronous Infinite loop on a Python Django server?
Consider the following code: import asyncio, aiohttp async def get_access_token(session, token): url = ... headers = ... data = ... async with session.post(url, headers=headers, data=data) as res: return await res.text() async def get_access_tokens(credentials): async with aiohttp.ClientSession() as session: tasks = [] for token in credentials: task = asyncio.create_task(get_access_token(session, token)) tasks.append(task) return await asyncio.gather(*tasks) async def main(): test = ... data = await get_access_tokens(test) print(data) if __name__ == '__main__': asyncio.run(main()) This code works as expected, but I need it to run in an infinite loop on a django server, so that it is executed every 2 hours (to update API access tokens) What is the pythonic way of running a script like this from a Django server? I can't seem to find anything on running code outside of a Django view. Any advice/links to related topics is appreciated. -
Chromedriver got ad error TypeError: environment can only contain strings
I'm using Selenium to open a Chrome Web Page with a user-agent, whitout Celery all is ok but when I call a def with Celery i got an error: app = Celery() @app.task(bind=True) def test(self, post_id): lui = Author.objects.get(pk=post_id) print lui.pk opts = Options() opts.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1') dri = r"C:\chromedriver.exe" driver =webdriver.Chrome(executable_path=r'C:\chromedriver.exe', chrome_options=opts) the error: Traceback (most recent call last): File "c:\python27\lib\site-packages\celery\app\trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "c:\python27\lib\site-packages\celery\app\trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "pathto\test.py", line 129, in test driver =webdriver.Chrome(executable_path=r'C:\chromedriver.exe', chrome_options=opts) File "c:\python27\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__ self.service.start() File "c:\python27\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start stdin=PIPE) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 658, in __init__ reraise(*exc_info) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 627, in __init__ restore_signals, start_new_session) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 1028, in _execute_child startupinfo) TypeError: environment can only contain strings Any suggest? -
What does this Apache HTTP rewrite rule do?
I'm looking to next block invalid HTTP_HOST headers at a server level on my Elastic Beanstalk Django app. Spammers keep hitting my website with invalid host headers (like HOST_HEADER = bad.com) and I want to block them at a server level (as compared to at a Django level). I found the following Apache server configuration here. I'm trying to figure out what this last RewriteRule is doing files: "/etc/httpd/conf/http-redirect.conf": mode: "000644" owner: root group: root content: | RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} It appears that RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} is forcing you to go the url that you have set as your HTTP_HOST, preventing you from hosting the website good.com at another domain like bad.com, as it redirects you to bad.com if that's what you've set as the host. If you don't set this line, it looks like the default setting would be RewriteRule (.*) https://good.com%{REQUEST_URI}. Am I correct in my understanding of this RewriteRule, and would using this config be an appropriate method of deflecting constant stream of invalid hosts? Potentially helpful for future searchers, here is my current .config file, which redirects to HTTPS: files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: … -
Serializing Django. How to set custom template
Good day! Trying to figure out how to generate xml in Django What do i have? Objects that appear on the site. The data of these objects must be generated in special fields in the xml file. I created views.py: def xml(request): listings = Listing.objects.all().filter(is_published=True) listings = serializers.serialize('xml', listings) context = { 'listings': listings } return HttpResponse(listings, content_type='application/xhtml+xml') As a result, I get: <django-objects version="1.0"> <object model="listings.Listing" pk="1"> <field name="price" type="IntegerField">100</field> </object> <object model="listings.Listing" pk="2"> <field name="price" type="IntegerField">100</field> </object> </django-objects> As I understand it, this is a standard template in Django Question! How to specify a custom template so that all markup is implemented by me, for example: <offer id="1"> <price>100</price> </offer> <offer id="2"> <price>100</price> </offer> Thank you in advance!